【问题标题】:Authorization Issue with JWT token creation Method (User Roles)JWT 令牌创建方法(用户角色)的授权问题
【发布时间】:2018-03-01 06:42:50
【问题描述】:

下面我有一个有效的 JWT 令牌创建方法,它可以在方法顶部没有授权标记的情况下工作。我还创建了在我之前实现令牌之前工作的用户角色。我相信自从令牌实现方法以来,我一直无法按角色配置授权,而是代码认为任何授权都需要 JWT 令牌。当我将令牌传递给邮递员时,身份验证将在简单的[Authorize] 下工作。但我需要限制创建令牌方法,以便只有注册用户才能使用它。

 [Authorize(Roles = "Users")]
        [HttpPost("api/auth/token")]
        public async Task<IActionResult> CreateToken([FromBody]
        CredentialViewModel model)
        {

            try
            {
                var user = await userManager.FindByNameAsync(model.UserName);

                if (user != null)
                {
                    if (_hasher.VerifyHashedPassword(user, user.PasswordHash, model.Password) == PasswordVerificationResult.Success)
                    {
                        // Get the claims from the user
                        var userClaims = await userManager.GetClaimsAsync(user);

                        var claims = new[] {
              new Claim(JwtRegisteredClaimNames.Sub, user.UserName),
              new Claim(JwtRegisteredClaimNames.Jti, user.APIKey.ToString()),
              new Claim(JwtRegisteredClaimNames.Email, user.Email??"")
            }.Union(userClaims);

                        //*********************************

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


                        var token = new JwtSecurityToken(
                          issuer: _config["Tokens:Issuer"],
                          audience: _config["Tokens:Audience"],
                          claims: claims,
                          expires: DateTime.UtcNow.AddDays(10),
                          signingCredentials: creds
                          );


                        return Ok(new
                        {
                            token = new JwtSecurityTokenHandler().WriteToken(token),
                            expiration = token.ValidTo

                        });

                    }

                }


            }
            catch (Exception ex)
            {

                _logger.LogError($"Exception thrown while creating JWT: {ex}");
            }

            return BadRequest();

        }

示例 json 输入

{
    "username" : "user02",
    "password" : "test123"
}

【问题讨论】:

    标签: c# asp.net authorization jwt postman


    【解决方案1】:

    确保在验证 JWT 令牌的位置或 Startup.cs 文件中正确设置 RoleClaimType 值。

    using System.Security.Claims;
    

    ....

    var tokenValidationParameters = new TokenValidationParameters
    {
      ......
      .....
      RoleClaimType = ClaimTypes.Role
    };
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-09-13
      • 1970-01-01
      • 1970-01-01
      • 2020-09-13
      • 2017-06-24
      • 2020-11-17
      • 2019-07-26
      • 2017-12-14
      相关资源
      最近更新 更多