Warm tip: This article is reproduced from serverfault.com, please click

asp.net core-System.Web.Security.FormsAuthenticationTicket的AspNetCore替代

(asp.net core - AspNetCore alternative for System.Web.Security.FormsAuthenticationTicket)

发布于 2020-11-30 10:41:47

我们正在使用System.Web.Security.FormsAuthenticationTicket为未登录的用户创建匿名cookie。AspNetCore是否具有等效功能?我知道ASP.NET Core不支持表单身份验证。做事的新方法是cookie。那么,如何创建在新情况下等效的cookie?

Questioner
MrFox
Viewed
11
Karney. 2020-12-18 09:53:52

Asp.net核心不支持表单身份验证。我建议你使用基于cookie的身份验证。链接可以帮助你构建它。

如果要跳过需要授权访问的方法。你可以添加attribute [AllowAnonymous]

    [AllowAnonymous]
    public IActionResult Privacy()
    {
        return View();
    }

或者,你可以参考此链接

在Startup.cs中配置cookie。

services.AddAuthentication("auth")
            .AddCookie("auth",config=>
            {
                config.Cookie.Name = "cookie.name";
                config.LoginPath = "/home/login";
            });

在此操作中生成令牌。你可以通过接收表单数据来填写索赔。

[HttpPost]
public IActionResult login()
    {
        var claims = new List<Claim>
        {
            new Claim(ClaimTypes.Name,"myName"),
            new Claim(ClaimTypes.Role,"myRole")
        };
        var claimIdentity = new ClaimsIdentity(claims,"id card");
        var claimPrinciple = new ClaimsPrincipal(claimIdentity);
        var authenticationProperty = new AuthenticationProperties
        {
            IsPersistent = true
        };
        HttpContext.SignInAsync(claimPrinciple,authenticationProperty);
        
        return View();
    }