简体   繁体   中英

Asp.Net MVC 6 Cookie Authentication - Authorization fails

I'm trying to create asp.net core mvc 6 app using Cookie Middleware authentication. My code compiles without errors, but even after successful login i'm not authorized user

Here's my startup.cs configuration

        app.UseCookieAuthentication(options =>
        {
            options.AuthenticationScheme = "CookieAuth";
            options.LoginPath = new PathString("/Account/Login/");
            options.AccessDeniedPath = new PathString("/Account/Login/");
            options.AutomaticAuthenticate = true;
            options.AutomaticChallenge = true;

        });

Also login action in my controller:

   public async Task<IActionResult> Login(LoginViewModel model)
    {

        User foundUser = _userManager.findUser(model.UserName, model.Password);


        if (foundUser != null)
        {
            List<Claim> userClaims = new List<Claim>
            {
                new Claim("userId", Convert.ToString(foundUser.UserID)),
                new Claim(ClaimTypes.Name, foundUser.UserName),
                new Claim(ClaimTypes.Role, Convert.ToString(foundUser.RoleID))
            };

            ClaimsPrincipal principal = new ClaimsPrincipal(new ClaimsIdentity(userClaims));
            await HttpContext.Authentication.SignInAsync("CookieAuth", principal);


            return RedirectToAction("Index", "Dashboard");
        }
        return View();
    }

And finally Dashboard/Index action

[Authorize]
public IActionResult Index()
{
    return View();
}

I put some breakpoints in login action and everything seems works fine. Cookie is also set correctly.

And now I don't know way i can't go to dashboard/index after sign in. Each time i'm redirected to /Account/Login/ due to configuration settings

What am I doing wrong ?

When you construct your ClaimsIdentity in your login, you need to use a different constructor that specifies the authenticationType .

Instead of

ClaimsPrincipal principal = new ClaimsPrincipal(new ClaimsIdentity(userClaims));

You should do:

ClaimsPrincipal principal = new ClaimsPrincipal(new ClaimsIdentity(userClaims, "local"));

It is now possible to create a ClaimsIdentity that has claims, but having IsAuthenticated set to false. Actually this is the default now...

To have IsAuthenticated set to true, you need to specify an authentication type

I got this info from Dominick Baier's blog here .

There is also a great example of using the cookie middleware here , also by (the legendary) Dominick Baier / leastprivilege.

EDIT:

This answer contains more information about what should be used for the authenticationType string.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM