0

I am having an issue where by setting RoleClaimType = "role" (lower case name) is causing the mismatch in RoleClaimType from the JWT token

For example jwt fields below note the role claim name in lower case, this fails to validate

{
    "iss": "xyz",
    "iat": 1625061220,
    "exp": 1656597220,
    "aud": "www.example.com",
    "sub": "test@example.com",
    "role": "Read"
}

However following passes validation (note PascalCase for Role)

{
    "iss": "xyz",
    "iat": 1625061220,
    "exp": 1656597220,
    "aud": "www.example.com",
    "sub": "test@example.com",
    "Role": "Read"
}

Following code in the application is used with RoleClaimType = "role"

public void ConfigureServices(IServiceCollection services)
{
    IdentityModelEventSource.ShowPII = true;
    services.AddMvcCore();
    services.AddAuthentication(x =>
    {
        x.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
        x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
        x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
    }).AddJwtBearer(JwtBearerDefaults.AuthenticationScheme, x =>
    {
                
        x.RequireHttpsMetadata = false;
        x.SaveToken = false;
        x.TokenValidationParameters = new TokenValidationParameters
        {
            RoleClaimType = "role",
            ValidateIssuerSigningKey = false,
            IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes("REPLACE_WTIH_YOUR_KEY")),
            ValidateLifetime = false,
            ValidateIssuer = false,
            ValidateAudience = false,
            ClockSkew = TimeSpan.Zero
        };
        x.Events = new JwtBearerEvents()
        {
            OnAuthenticationFailed = c =>
            {
                c.NoResult();

                c.Response.StatusCode = 500;
                c.Response.ContentType = "text/plain";
                return c.Response.WriteAsync(c.Exception.ToString());
            }
        };
    });
    services.AddAuthorization();
    services.AddHttpContextAccessor();
}

Any idea?

shobhonk
  • 621
  • 5
  • 15

2 Answers2

0

It may be a problem with JwtSecurityTokenHandler performing inbound "type" mapping.

You can disable mapping at the application level:

JwtSecurityTokenHandler.DefaultMapInboundClaims = false;

Or use options.ClaimsIdentity.RoleClaimType = "role";

And add Authorize(Roles = "myRoleName")

Or you can verify by reading the JSON configuration, as in this post:ASP.NET Core JWT mapping role claims to ClaimsIdentity

Tupac
  • 2,590
  • 2
  • 6
  • 19
0

Remove RoleClaimType = "role" line

al s
  • 1
  • 1