简体   繁体   中英

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 . 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.

    //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承载验证,验证和解码的令牌,最后写用户的原则。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM