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

AspNetCore alternative for System.Web.Security.FormsAuthenticationTicket

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

We're using System.Web.Security.FormsAuthenticationTicket to create anonymous cookies for users that aren't logged in. Is there an equivalent in AspNetCore? I'm well aware that ASP.NET Core cannot support forms authentication. The new way of doing things is cookies. So how to create a cookie that does the equivalent in the new situation?

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

Asp.net core cannot support form authentication. I recommend you use cookie-base authentication. This link can help you build it.

If you want to skip a method that requires authorized access. You can add attribute [AllowAnonymous].

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

Or you can refer to this link.

Configure cookie in Startup.cs.

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

Generate token in this action. You can fill the claim by receiving form data.

[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();
    }