Kuba Kuba - 1 year ago 132
ASP.NET (C#) Question

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

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 ?

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download