【问题标题】:Asp.Net MVC 6 Cookie Authentication - Authorization failsAsp.Net MVC 6 Cookie 身份验证 - 授权失败
【发布时间】:2016-05-29 11:11:57
【问题描述】:

我正在尝试使用Cookie Middleware 身份验证创建 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 也设置正确。

现在我不知道登录后我无法进入仪表板/索引。 每次由于配置设置我被重定向到 /Account/Login/

我做错了什么?

【问题讨论】:

    标签: c# asp.net asp.net-core


    【解决方案1】:

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

    代替

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

    你应该这样做:

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

    现在可以创建具有声明的 ClaimsIdentity,但是 将 IsAuthenticated 设置为 false。实际上这是现在的默认设置...

    要将 IsAuthenticated 设置为 true,您需要指定身份验证类型

    我从 Dominick Baier 的博客 here 获得此信息。

    还有一个很好的使用 cookie 中间件 here 的例子,也是由(传奇的)Dominick Baier / leastprivilege 编写的。

    编辑:

    This answer 包含有关 应该 用于authenticationType 字符串的更多信息。

    【讨论】:

    • 非常感谢!因为一个参数,我失去了 2 小时的生命 :(
    • 当之无愧的投票,感谢您的回答!浪费了 2 多个小时,但至少我知道为什么!
    • 在这上面花了 4 个小时。谢谢。 authenticationType 参数应该设置什么?是“Cookie”、“JWT”还是使用的方案之类的?
    • 谢谢!我因这个问题损失了 3 小时。
    猜你喜欢
    • 1970-01-01
    • 2011-03-12
    • 2021-06-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-19
    • 1970-01-01
    相关资源
    最近更新 更多