Asp.Net MVC 6 Cookie身份验证 - 授权失败

15
我正在尝试使用Cookie中间件身份验证创建asp.net core mvc 6应用程序。我的代码编译没有错误,但即使成功登录,我也没有被授权用户。
这是我的startup.cs配置:
        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();
    }

最后是仪表板/索引操作

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

我在登录操作中设置了一些断点,一切似乎都正常。 Cookie也设置正确。

现在我不知道为什么我无法在登录后进入仪表板/索引页面。 每次都由于配置设置而被重定向到/账户/登录/

我做错了什么?

1个回答

18

在登录时构建ClaimsIdentity时,您需要使用指定authenticationType的不同构造函数。

而不是使用原来的构造函数。

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

你应该做:

ClaimsPrincipal principal = new ClaimsPrincipal(new ClaimsIdentity(userClaims, "local"));
现在可以创建一个具有声明的ClaimsIdentity,但将IsAuthenticated设置为false。实际上,这是现在的默认值...要将IsAuthenticated设置为true,您需要指定身份验证类型。
我从Dominick Baier的博客(此处)获取了这些信息。
还有一个很好的使用cookie中间件的示例,由(传说中的)Dominick Baier / leastprivilege提供,(此处)
编辑:此答案包含有关应使用的authenticationType字符串的更多信息。


2
非常感谢!因为一个参数,我浪费了2个小时的生命:( - Kuba
1
非常值得的点赞,感谢您的回答!虽然浪费了2个小时,但至少我知道原因了! - Radu Grama
1
我花了4个小时在这上面。谢谢。authenticationType参数应该设置为什么?是“Cookie”,“JWT”还是使用的方案或其他任何东西? - Omar
@Omar - 这里有更多的信息 https://dev59.com/9mIj5IYBdhLWcg3wcEuI#30430228 - Jamie Dunstan
1
最后一个链接已经失效,很可能指向 https://github.com/leastprivilege/AspNetCoreSecuritySamples/tree/master/Cookies/src/AspNetCoreAuthentication。 - michaelmsm89
1
谢谢!我因这个问题浪费了3个小时。 - Thiago Silva

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接