C# Asp.Net MVC 6 Cookie身份验证-授权失败
我正在尝试使用身份验证创建asp.net核心mvc 6应用程序。 我的代码编译没有错误,但即使在成功登录后,我也不是授权用户 这是我的startup.cs配置C# Asp.Net MVC 6 Cookie身份验证-授权失败,c#,asp.net,asp.net-core,C#,Asp.net,Asp.net Core,我正在尝试使用身份验证创建asp.net核心mvc 6应用程序。 我的代码编译没有错误,但即使在成功登录后,我也不是授权用户 这是我的startup.cs配置 app.UseCookieAuthentication(options => { options.AuthenticationScheme = "CookieAuth"; options.LoginPath = new PathString("/Acco
app.UseCookieAuthentication(options =>
{
options.AuthenticationScheme = "CookieAuth";
options.LoginPath = new PathString("/Account/Login/");
options.AccessDeniedPath = new PathString("/Account/Login/");
options.AutomaticAuthenticate = true;
options.AutomaticChallenge = true;
});
在我的控制器中还有登录操作:
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();
}
我在登录操作中设置了一些断点,似乎一切正常。
Cookie也设置正确
现在我不知道在登录后如何无法进入仪表板/索引。
每次由于配置设置而重定向到/Account/Login/时
我做错了什么?当您在登录中构造
索赔实体时,您需要使用另一个构造函数来指定身份验证类型
而不是
ClaimsPrincipal principal = new ClaimsPrincipal(new ClaimsIdentity(userClaims));
你应该做:
ClaimsPrincipal principal = new ClaimsPrincipal(new ClaimsIdentity(userClaims, "local"));
现在可以创建一个具有索赔的索赔实体,但是
已被验证的设置为false。实际上,这是默认的现在
要将IsAuthenticated设置为true,需要指定身份验证类型
我从Dominick Baier的博客上得到了这些信息
还有一个使用cookie中间件的好例子,也是由(传奇人物)Dominick Baier/leastprivilege提供的
编辑:
包含有关应用于authenticationType
字符串的内容的详细信息。非常感谢!因为一个参数,我失去了2个小时的生命:(当之无愧的投票,谢谢你的回答!失去了2个多小时,但至少我知道为什么!在这上面花了4个小时。谢谢。应该为authenticationType
参数设置什么?是“Cookie”、“JWT”吗或者使用了什么方案?最后一个链接断了,很可能是指向谢谢!我因为这个问题失去了3小时。
ClaimsPrincipal principal = new ClaimsPrincipal(new ClaimsIdentity(userClaims, "local"));