【问题标题】:Using Identity with token and cookie authentication将 Identity 与令牌和 cookie 身份验证一起使用
【发布时间】:2018-04-22 04:25:58
【问题描述】:

我正在尝试在我的应用程序中同时设置令牌身份验证和 cookie 身份验证。

我在 asp.net core 2.0 中创建了一个 MVC 项目,使用个人用户帐户进行身份验证。也为用户设置角色。

如果我按照 Shawn Wildermuth 的教程 Two-AuthorizationSchemes-in-ASP-NET-Core-2

获取注册用户的 Token 一切正常。但是,如果我在授权 [Authorize(Roles="Admin")] 上使用 Role 属性,我会得到 403 响应。

我认为这是因为令牌没有收到身份验证角色。

如何设置?有什么方法可以在令牌过程中传递角色吗?

要生成他正在使用这段代码的令牌:

[AllowAnonymous] 
[HttpPost] 
public async Task<IActionResult> GenerateToken([FromBody] LoginViewModel model) {   if (ModelState.IsValid)   {
        var user = await _userManager.FindByEmailAsync(model.Email);

        if (user != null)
        {
          var result = await _signInManager.CheckPasswordSignInAsync(user, model.Password, false);
          if (result.Succeeded)
          {

            var claims = new[]
            {
              new Claim(JwtRegisteredClaimNames.Sub, user.Email),
              new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
            };

            var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config["Tokens:Key"]));
            var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);

            var token = new JwtSecurityToken(_config["Tokens:Issuer"],
              _config["Tokens:Issuer"],
              claims,
              expires: DateTime.Now.AddMinutes(30),
              signingCredentials: creds);

            return Ok(new { token = new JwtSecurityTokenHandler().WriteToken(token) });
          }
        }   }

      return BadRequest("Could not create token"); }

你们有什么想法吗?

谢谢

【问题讨论】:

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


    【解决方案1】:

    如果您添加以下使用和代码,那应该会有所帮助。

    using System.Security.Claims;
    

    ...

        var userRoles = await _userManager.GetRolesAsync(user);
    
        var claims = new[]
            {
              new Claim(JwtRegisteredClaimNames.Sub, user.Email),
              new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
            }.Union(userRoles.Select(m => new Claim(ClaimTypes.Role, m)));
    

    您可以看到将角色添加到ClaimTypes.Role类型中的Union,这将使它们能够在AuthorizeAttribute中使用

    HTH

    【讨论】:

    • 嗨,它不起作用....它说用户没有角色定义...谢谢
    • 抱歉,我认为您显然需要将 user.Roles 替换为您自己的如何为用户获取角色的实现。如果您更喜欢快速 PoC,您可以手动将角色添加到代码中以查看它是否有效
    • 嗨...我设法做到了这一点:在 generateToken 方法中,我首先获得了用户角色:var userRoles = await _userManager.GetRolesAsync(user);在声明中,我添加: new Claim(ClaimTypes.Role, userRoles.FirstOrDefault()) 添加要声明的角色。但问题是,如果用户拥有多个角色,我只会得到第一个。 :-(
    • 这就是 first 或 default 会做的事情。我已经更新了答案中的代码以使用您正在填充的 userRoles 对象。看看效果是否更好
    猜你喜欢
    • 2014-01-24
    • 1970-01-01
    • 2012-07-03
    • 2016-03-01
    • 1970-01-01
    • 2020-06-06
    • 1970-01-01
    • 1970-01-01
    • 2015-10-29
    相关资源
    最近更新 更多