Home > Back-end >  Dotnet JWT Bearer TokenValidationParameters issue - Unauthorized? Role(Policy) based authorization d
Dotnet JWT Bearer TokenValidationParameters issue - Unauthorized? Role(Policy) based authorization d

Time:11-08

I changed the setting in the TokenValidationParameters (ValidateIssuer,ValidateAudience) from False to True.

What the settings used to be (startup) - everything was working perfectly.

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

Now every call to the API the requires to authorized stopped working.

The new settings - stopped working

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

Every call to the API that needs to be authorized now is getting unauthorized.

This is my token service:

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

Does anyone can please explain to me what causes it so I could learn. And how can I fix it ? I tried many ways but unfortunately, nothing seems to work for me. Thank you so much.

This is the code at GitHub just in case : https://github.com/davidax0204/HeroMain.git

CodePudding user response:

When you set ValidateIssuer and ValidateAudience to true, you should set value for ValidIssuer and ValidAudience when creating JWT and SecurityTokenDescriptor

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

And adding same value to TokenValidationParameters properties

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"
                };
            });
  • Related