3

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?

0

1 Answer 1

4

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();
    }
Sign up to request clarification or add additional context in comments.

3 Comments

Of course I'm looking for a cookie alternative. I'll edit the original question.
@MrFox, add cookie configuration, then generate the token.
@MrFox, can you accept this answer, or have any other issues?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.