ASP.NET Core WebApi Jwt 基于角色的授权不起作用

Posted

技术标签:

【中文标题】ASP.NET Core WebApi Jwt 基于角色的授权不起作用【英文标题】:ASP.NET Core WebApi Jwt Role-based Authorization not working 【发布时间】:2019-09-29 19:06:00 【问题描述】:

我已经根据一个教程实现了一个 JWT 身份验证/授权系统。

但不幸的是,我不知道如何授权角色。

这是基于角色的授权。

    public class InfoController : ControllerBase
    
        [Authorize(Roles = "User")]
        [HttpGet("user")]
        public IActionResult UserInfo()
        
            return Ok("User role");
        
    

当我调用此 api/Info/user 时,我得到 401 响应代码,而不是状态代码 200 和“用户角色”消息。所以基于角色的授权不起作用。 我用正确的数据调用它:

curl -X GET "https://localhost:34545/api/Info/user" -H  "accept: application/json" -H  "Authorization: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJ0ZXN0IiwianRpIjoiYTgwYzQ3NDQtNmYyZC00ZTAwLThhYjItMzY2MTRmYTNmMzYzIiwiaWF0IjoxNTU3NjgyMDU4LCJyb2wiOiJ3ZWItYXBpLWFjYyIsImh0dHA6Ly9zY2hlbWFzLm1pY3Jvc29mdC5jb20vd3MvMjAwOC8wNi9pZGVudGl0eS9jbGFpbXMvcm9sZSI6IlVzZXIiLCJuYmYiOjE1NTc2ODIwNTgsImV4cCI6MTU1NzY4OTI1OCwiaXNzIjoid2ViLWFwaSIsImF1ZCI6Imh0dHBzOi8vbG9jYWxob3N0OjQ0MzUwLyJ9.8uRAOsSXmKeWcYCwvN0sNFX02GNoZMaPNf6RPGkQE4E"

在启动时我有以下配置:

services.AddAuthorization(options =>
        
            options.AddPolicy("api", policy => policy.RequireClaim(
               jwtClaimConfiguration[nameof(JwtClaimOptions.Rol)],
               jwtClaimConfiguration[nameof(JwtClaimOptions.ApiAccess)]
            ));
            options.AddPolicy("user", policy => policy.RequireRole(AppRole.USER));
            options.AddPolicy("admin", policy => policy.RequireRole(AppRole.ADMIN));
        );

Jwt 生成的地方(我在这里看到 *** 这个解决方案)

 public async Task<string> GenerateEncodedTokenAsync(string userName, ClaimsIdentity claimsIdentity)
        
            List<Claim> claims = new List<Claim>()
            
                 new Claim(JwtRegisteredClaimNames.Sub, userName),
                 new Claim(JwtRegisteredClaimNames.Jti, await jwtOptions.JtiGenerator()),
                 new Claim(JwtRegisteredClaimNames.Iat, ToUnixEpochDate(jwtOptions.IssuedAt).ToString(), ClaimValueTypes.Integer64),
                 claimsIdentity.FindFirst(jwtClaimConfiguration[nameof(JwtClaimOptions.Rol)]),
                 claimsIdentity.FindFirst(jwtClaimConfiguration[nameof(JwtClaimOptions.ApiAccess)])
             ;
            var user = await userManager.FindByNameAsync(userName);
            var roles = await userManager.GetRolesAsync(user);

            claims.AddRange(roles.Select(role => new Claim(ClaimsIdentity.DefaultRoleClaimType, role)));

            JwtSecurityToken jwt = new JwtSecurityToken(
                issuer: jwtOptions.Issuer,
                audience: jwtOptions.Audience,
                notBefore: jwtOptions.NotBefore,
                expires: jwtOptions.Expiration,
                signingCredentials: jwtOptions.SigningCredentials,
                claims: claims
            );

            return new JwtSecurityTokenHandler().WriteToken(jwt);
        

Jwt 令牌包含角色!这是有效负载,您可以看到已添加角色,用户具有“用户”角色。:


  "sub": "demo",
  "jti": "a80c4744-6f2d-4e00-8ab2-36614fa3f363",
  "iat": 1557682058,
  "rol": "acc",
  "http://schemas.microsoft.com/ws/2008/06/identity/claims/role": "User",
  "nbf": 1557682058,
  "exp": 1557689258,
  "iss": "api",
  "aud": "https://localhost:34545/"

【问题讨论】:

看看this 的帖子。我认为您缺少启动文件中的身份验证配置,即services.AddAuthentication(...)services.AddJwtBearer(...) 调用。此外,在传递 Authorization 标头时,您在 Jwt 令牌之前缺少 Bearer 【参考方案1】:

请以正确的方式订购中间件

 first =>  app.UseRouting();
 second => app.UseAuthentication();
 third=>  app.UseAuthorization();

【讨论】:

以上是关于ASP.NET Core WebApi Jwt 基于角色的授权不起作用的主要内容,如果未能解决你的问题,请参考以下文章

ASP.NET Core WebApi Jwt 基于角色的授权不起作用

ASP.NET Core JWT 身份验证以保护 webAPI [Authorize] 属性错误 401 Unauthorized

[WebApi]ASP.Net Core 中使用JWT认证(3.1版本,5.0也可以使用)

[WebApi]ASP.Net Core 中使用JWT认证(3.1版本,5.0也可以使用)

带有 JWT Bearer 令牌和 ASP.NET Core 2 WebApi 的 Azure AD 用户信息

从 ASP.NET Core 中的 API 读取 JWT 令牌