简体   繁体   English

基于 ASP.NET Core 3.1 Web API 角色的授权不起作用

[英]ASP.NET Core 3.1 Web API Role based authorization not working

I couldn't understand why I always get 401 unauthorized where the user I logged in has a role of SuperAdmin .我不明白为什么我总是在我登录的用户具有SuperAdmin角色的情况下获得401 未经授权 I tried looking at other solutions and projects and they seem identical to the code I have still does not work.我尝试查看其他解决方案和项目,但它们似乎与我的代码相同,但仍然无法正常工作。 I use Postman to test the API and in Authorization tab bearer token I pasted the token of the user I logged in and make a request on this API.我使用 Postman 来测试 API,并在授权选项卡不记名令牌中粘贴了我登录的用户的令牌并在此 API 上发出请求。

    //API
    [Route("create")]
    [Authorize(Roles = "SuperAdmin")]
    public async Task<IActionResult> RegisterUserAsync([FromBody] Request request)
    {
       return something;
    }

    //StartUp.cs
    private void ConfigureAuth(IServiceCollection services)
    {
        services.AddIdentity<UserEntity, RoleEntity>()
            .AddEntityFrameworkStores<ApplicationDbContext>()
            .AddDefaultTokenProviders()
            .AddRoles<RoleEntity>();
    }
    var key = Encoding.ASCII.GetBytes(jwtSettings.Secret);
        services.AddAuthentication(x =>
        {
            x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
            x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
        })
        .AddJwtBearer(x =>
        {
            x.RequireHttpsMetadata = false;
            x.SaveToken = true;
            x.TokenValidationParameters = new TokenValidationParameters
            {
                ValidateIssuerSigningKey = true,
                IssuerSigningKey = new SymmetricSecurityKey(key),
                ValidateIssuer = false,
                ValidateAudience = false
            };
        });

    //JWT
    public string GenerateToken(UserEntity userEntity, IList<string> roles)
    {
        var token = string.Empty;
        var tokenHandler = new JwtSecurityTokenHandler();
        var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(this.jwtOptions.GetJwtOptions().Secret));
        var credentials = new SigningCredentials(key, SecurityAlgorithms.HmacSha256Signature);

        var claims = new List<Claim>()
        {
            new Claim(ClaimTypes.Name, userEntity.UserName),
            new Claim(ClaimTypes.GivenName, userEntity.FirstName),
            new Claim(ClaimTypes.Surname, userEntity.LastName),
            new Claim(ClaimTypes.NameIdentifier, userEntity.Id.ToString()),
            new Claim(ClaimTypes.Role, roles.FirstOrDefault()) //SuperAdmin
        };

        var tokenDescriptor = new SecurityTokenDescriptor
        {
            Subject = new ClaimsIdentity(claims),
            Expires = DateTime.UtcNow.AddMinutes(this.jwtOptions.GetJwtOptions().ExpiresInMinutes),
            SigningCredentials = credentials
        };

        token = tokenHandler.WriteToken(tokenHandler.CreateToken(tokenDescriptor));

        return token;
    }

您需要添加app.UseAuthentication()之前app.UseAuthorization()认证中间件将处理JWT承载验证,验证和解码的令牌,最后写用户的原则。

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

相关问题 ASP.NET Core 3.1 中基于角色的授权,带有身份和外部登录 - Role based authorization in ASP.NET Core 3.1 with Identity and ExternalLogin ASP.NET Core 3.0 基于角色的授权不起作用 - ASP.NET Core 3.0 Role Based Authorization not working 基于角色的授权属性在 ASP.NET Core MVC 中不起作用 - Role based authorization attribute not working in ASP.NET Core MVC IdentityServer4 基于角色的 Web API 授权与 ASP.NET Core 标识 - IdentityServer4 Role Based Authorization for Web API with ASP.NET Core Identity 角色授权不适用于 React/ASP.NET Core API - Role Authorization Not Working with React/ASP.NET Core API 具有基于角色的授权的ASP.NET Web Api - ASP.NET Web Api with Role based authorization 使用 .NET Core Web API 3.1 的 JWT 基于角色的授权时出现 403 错误 - 403 Error on JWT Role Based Authorization using .NET Core Web API 3.1 ASP.NET Core 3.1 Web API 中的“授权失败。AuthenticationScheme:AzureADJwtBearer 受到挑战” - 401 Unauthorized - "Authorization failed. AuthenticationScheme: AzureADJwtBearer was challenged" in ASP.NET Core 3.1 Web API - 401 Unauthorized ASP.NET 内核 3.1 Web Api 对 Z20F35E630DAF449DBFA4C3F6885 级别的授权 - ASP.NET Core 3.1 Web Api authorization on model property level 基于路由参数的基于ASP.NET Web API角色的授权 - ASP.NET Web API role based authorization based on route parameter
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM