JWT令牌创建方法的授权问题(用户角色)

时间:2017-09-20 09:20:08

标签: c# asp.net authorization jwt postman

下面我有一个有效的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"
}

1 个答案:

答案 0 :(得分:0)

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

using System.Security.Claims;

...

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