Search code examples
asp.net-coreasp.net-identityclaims-based-identity

Custom claims with Jwt Bearer Authentication


I have an application that uses JwtBearerAuthentication. I am trying to add my application claims to the User(ClaimsPrincipal) at the beginning of each request. I managed to do that using ClaimsTransformationOptions:

app.UseClaimsTransformation(new ClaimsTransformationOptions
{
    Transformer = new ClaimsTransformer<TUser, TRole>()
});

and in my TransformAsync:

public async Task<ClaimsPrincipal> TransformAsync(ClaimsTransformationContext context)
{
    var services = context.Context.RequestServices;
    var userManager = services.GetRequiredService<UserManager<TUser>>();
    var roleManager = services.GetRequiredService<RoleManager<TRole>>();

    var userId = 1; // Get the UserId from my store, let say its 1 for now

    if (userId != 0)
    {
        var user = await userManager.FindByIdAsync(userId);

        var claimsPrincipal = await new UserClaimsPrincipalFactory<TUser, TRole>(userManager, roleManager, _optionsAccessor)
                .CreateAsync(user);

        context.Principal.AddIdentities(claimsPrincipal.Identities);
    }

    return context.Principal;
}

So far so good and the claims are being loaded from the database and added to the context.Principal. My problem is once I reach the controller, the identities are being overwritten !!


Solution

  • So I solved this problem by putting the app.UseClaimsTransformation after app.UseJwtBearerAuthentication which made sure that whenever JWT is going to amend the ClaimsPrincipal the ClaimsTransformation will be called afterwards to add my own claims.