【问题标题】:Controller not recognizing JWT roles .net core 5控制器无法识别 JWT 角色.net core 5
【发布时间】:2021-08-10 03:58:42
【问题描述】:

我已经在我的 .net 核心应用程序中设置了授权和身份验证。我正在创建我的 JWT 令牌并添加一个角色:

 public async Task<IActionResult> Login([FromBody] LoginModel model)
    {
        var user = await userManager.FindByNameAsync(model.Username);
        if(user!=null && await userManager.CheckPasswordAsync(user, model.Password))
        {
            var authClaims = new[]
            {
                new Claim(JwtRegisteredClaimNames.Sub, user.UserName),
                new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
                new Claim(ClaimTypes.Role,"Employee")
            };
            var authSignKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("*******************"));
            var token = new JwtSecurityToken(
                issuer: "https://example.com",
                audience: "https://example.com",
                expires: DateTime.Now.AddDays(5),
                claims: authClaims,
                signingCredentials: new Microsoft.IdentityModel.Tokens.SigningCredentials(authSignKey, SecurityAlgorithms.HmacSha256)
                );
            return Ok(new
            {
                token = new JwtSecurityTokenHandler().WriteToken(token),
                expiration = token.ValidTo
            });
        }
        return Unauthorized();
    }

我现在添加了声明类型角色并分配给“员工”。在我的控制器中,我有这个:整个控制器上的装饰:

 [Authorize(Roles ="Employee")]
[ApiController]
[Route("[controller]")]

我也只是将 Authorize 放在控制器上,将 Authorize(Roles="Employee") 放在我正在使用的 Get() 方法上。我可以生成 JWT,当我在 Jwt.io 上查看它时,我会看到:

 {
  "sub": "test",
  "jti": "f3c204d4-151f-402a-bdf5-6574934d4644",
  "http://schemas.microsoft.com/ws/2008/06/identity/claims/role": "Employee",
  "exp": 1621968453,
  "iss": "https://example.com",
  "aud": "https://example.com"
}

所以它正在被编码。我看不到我缺少什么,我需要为登录分配角色以控制对方法的访问。

【问题讨论】:

    标签: .net .net-core jwt


    【解决方案1】:

    发现了问题,我想我会分享。我检查了 startup.cs 文件以确保 app.UseAuthentication() 和 app.UseAuthorization() 的顺序正确。他们是。接下来,我检查了拼写以确保角色正确。它是。发现问题是startup.cs文件中的ValidAudience和ValiIssuer与登录控制器中的token生成不同。我通过捕获调用的返回标头找到了它并发现了错误。将控制器中的令牌创建者切换到正确的发行者/受众,并且它可以工作。

    我发布这个是因为很多答案都是为了检查 startup.cs 文件中的顺序。这是要检查的不同区域。

    【讨论】:

      猜你喜欢
      • 2018-07-18
      • 2019-05-11
      • 2020-07-26
      • 1970-01-01
      • 2018-11-11
      • 2016-05-30
      • 1970-01-01
      • 2020-11-11
      • 2021-06-16
      相关资源
      最近更新 更多