Dotnet JWT Bearer TokenValidationParameters 问题 - 未经授权?基于角色(策略)的授权不起作用

Dotnet JWT Bearer TokenValidationParameters issue - Unauthorized? Role(Policy) based authorization doesnt work

我将 TokenValidationParameters (ValidateIssuer,ValidateAudience) 中的设置从 False 更改为 True。

以前的设置(启动) - 一切正常。

services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
            .AddJwtBearer(options =>
            {
                options.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuerSigningKey = true,
                    IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(config["TokenKey"])),
                    ValidateIssuer = false,
                    ValidateAudience = false,
                };
            });

现在每次调用 API 授权要求都停止工作。

新设置 - 停止工作

services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
            .AddJwtBearer(options =>
            {
                options.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuerSigningKey = true,
                    IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(config["TokenKey"])),
                    ValidateIssuer = true,
                    ValidateAudience = true,
                };
            });

现在对 API 的每个需要授权的调用都在未经授权。

这是我的令牌服务:

    public class TokenService : ITokenService
{
    private readonly SymmetricSecurityKey _key;
    private readonly UserManager<AppUser> _userManager;

    public TokenService(IConfiguration config, UserManager<AppUser> userManager)
    {
        this._userManager = userManager;
        _key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(config["TokenKey"]));
    }
    public async Task<string> CreateToken(AppUser user)
    {
        var claims = new List<Claim>
        {
            new Claim(JwtRegisteredClaimNames.NameId, user.Id.ToString()),
            new Claim(JwtRegisteredClaimNames.UniqueName, user.UserName)
        };

        var roles = await _userManager.GetRolesAsync(user);

        claims.AddRange(roles.Select(role => new Claim(ClaimTypes.Role, role)));

        var creds = new SigningCredentials(_key, SecurityAlgorithms.HmacSha512Signature);

        var tokenDescriptor = new SecurityTokenDescriptor
        {
            Subject = new ClaimsIdentity(claims),
            Expires = DateTime.Now.AddDays(7),
            SigningCredentials = creds
        };

        var tokenHandler = new JwtSecurityTokenHandler();

        var token = tokenHandler.CreateToken(tokenDescriptor);

        return tokenHandler.WriteToken(token);
    }
}

有谁能给我解释一下是什么原因造成的,以便我学习。我该如何解决?我尝试了很多方法,但不幸的是,似乎没有什么对我有用。 非常感谢。

这是 GitHub 处的代码,以防万一: https://github.com/davidax0204/HeroMain.git

当您将ValidateIssuerValidateAudience设置为true时,您应该在创建JWTValidIssuerValidAudience时设置值SecurityTokenDescriptor

var tokenDescriptor = new SecurityTokenDescriptor
        {
            Subject = new ClaimsIdentity(claims),
            Expires = DateTime.Now.AddDays(7),
            SigningCredentials = creds,
            Audience = "YourAudience",
            Issuer = "YourIssuer"
        };

并向 TokenValidationParameters 属性添加相同的值

services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
            .AddJwtBearer(options =>
            {
                options.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuerSigningKey = true,
                    IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(config["TokenKey"])),
                    ValidateIssuer = true,
                    ValidIssuer = "YourIssuer",

                    ValidateAudience = true,
                    ValidAudience = "YourAudience"
                };
            });