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 ?
Best Answer
When you construct your
ClaimsIdentity
in your login, you need to use a different constructor that specifies theauthenticationType
.Instead of
You should do:
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.