简体   繁体   English

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

[英]ASP.NET Core WebApi Jwt Role-based Authorization not working

I have implemented a JWT Authentication/Authorization system based on a tutorial.我已经根据教程实现了 JWT 身份验证/授权系统。

But Unfortunately I have no idea how to authorize the roles.但不幸的是,我不知道如何授权这些角色。

This is a role based authorizaton.这是基于角色的授权。

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

When I call this api/Info/user I get 401 response code instead of the Status code 200 with the "User role" message.当我调用此api/Info/user时,我得到401响应代码而不是带有“用户角色”消息的状态代码200 So the role-based authorization does not work.所以基于角色的授权不起作用。 I call it with the correct data:我用正确的数据调用它:

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

In the startup I has the following configuration:在启动时我有以下配置:

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));
        });

Here where the Jwt generated (I have seen here StackOverflow this solution)这里生成Jwt(我在这里看到过StackOverflow这个解决方案)

 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);
        }

The Jwt token contains the role, Here is the payload, as you can see the Role has been added. Jwt 令牌包含角色,这是有效负载,如您所见,角色已添加。 the user has the "User" role::用户具有“用户”角色::

{
  "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/"
}

please order middleware in right way请以正确的方式订购中间件

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 使用 Windows 身份验证对 ASP.NET Core 基于角色的授权进行故障排除 - Troubleshooting ASP.NET Core Role-based Authorization with Windows Authentication 基于角色的授权在 Asp.Net Core 2.1 中不起作用 - Role-based authorization doesn't work in Asp.Net Core 2.1 基于角色的授权属性在 ASP.NET Core MVC 中不起作用 - Role based authorization attribute not working in ASP.NET Core MVC ASP.NET Core 3.0 基于角色的授权不起作用 - ASP.NET Core 3.0 Role Based Authorization not working .NET Core 3.1 基于角色的授权与 JWT 返回 403 禁止 - .NET Core 3.1 role-based authorization with JWT returns 403 forbidden 全栈应用中基于角色的 Active Directory 身份验证和授权(React.js + ASP.Net Core) - Role-based Active Directory authentication and authorization in full stack app (React.js + ASP.Net Core) 无法使用 ASP.NET Core 标识从基于角色的 HttpGet 请求中列出数据 - Unable to list data from Role-based HttpGet request using ASP.NET Core identity Asp.NET Core MVC基于角色的授权 - Asp.NET Core MVC Role based Authorization ASP.NET标识“基于角色”的声明 - ASP.NET Identity “Role-based” Claims ASP.NET Core 3.1 中基于角色的授权,带有身份和外部登录 - Role based authorization in ASP.NET Core 3.1 with Identity and ExternalLogin
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM