Search code examples
.netasp.net-coreasp.net-web-apiidentityserver4.net-8.0

Role Claim not working in ASP.NET Core 8 Web API after upgrading to .NET 8


I have a .NET 7 ASP.NET Core 7.0 Web API project which uses .NET 7 ASP.NET Core 7.0 IdentityServer4 Project. Everything is working fine.

Here is my code setup:

IdentityServer4:

In my ProfileService in IdentityServer4 project, I'm adding a role claim as show below.

ProfileService.cs:

claims.Add(new Claim("role", "master"));

Startup.cs:

JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear();

Web API:

I have added Authorization services in Program.cs

Program.cs:

JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear();

services.AddScoped<IAuthorizationHandler, SubjectMustMatchUserHandler>();

services.AddAuthorization(authorizationOptions =>
            {
                authorizationOptions.AddPolicy(
                Policies.SubjectMustMatchUser,
                policyBuilder =>
                {
                    policyBuilder.RequireAuthenticatedUser();
                    policyBuilder.AddRequirements(new SubjectMustMatchUserRequirement());
                });

                authorizationOptions.AddPolicy(Policies.MustBeMasterUser, Policies.MustBeMasterUserPolicy());
            })
        .AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
        .AddJwtBearer(options =>
        {
            options.Authority = configuration.GetValue<string>("AuthorityUrl");
            options.Audience = "redacted";
        });

Authorization Policy:

public static AuthorizationPolicy MustBeMasterUserPolicy()
{
    return new AuthorizationPolicyBuilder()
        .RequireAuthenticatedUser()
        .RequireClaim("role", "master")
        .Build();
}

Claims:

enter image description here

Till now all is working fine.

Now I have updated my project to .NET 8 and the Role Claim is not working as expected and my policies are failing.

When I debug, I noticed the change in the name of role claim key from role to http://schemas.microsoft.com/ws/2008/06/identity/claims/role as shown below

enter image description here

This change is making my policies to fail. I'm not able to find any docs to fix this in Migration guides. Please can you help me figure out what I'm missing?


Solution

  • You need to specify what the name of your role and name claim is, using:

    .AddJwtBearer(opt =>
    {
        // ...
        opt.TokenValidationParameters.RoleClaimType = "role";
        opt.TokenValidationParameters.NameClaimType = "name";
        // ...
    });
    

    You might also want to disable the rename of the claims, by:

    .AddJwtBearer(opt =>
    {
        // ...
        opt.MapInboundClaims = false;
        // ...
    });
    

    For more details, see my blog post here: Debugging JwtBearer Claim Problems in ASP.NET Core