Search code examples
.netasp.net-coreasp.net-web-api

How do I add or change claims in .NET using the new IClaimsTransformation interface


I know ClaimsAuthenticationManager was used in .NET Framework. I need to perform some custom logic to modify claims and make sure the modifications persist across requests


Solution

  • It is actually quite straightforward.

    Using IClaimsTransformation is the recommended approach. Do not hook into events such as Events.OnTokenValidated to modify the claim as you can have issues as the modified claims won't necessarily persist across requests. You may find that the claims still missing from httpContext.User across the requests.

    The other advantage is this is independent of authentication type. It executes in the pipeline for Jwt, OpenIdConnect etc

    Here is the basic example of the implementation. You can inject any service you may need into the constructor, such as a dbContext.

    The TransformAsync method will automatically be called passing in the principal.

    public class CustomClaimsTransformation : IClaimsTransformation
    {
        private readonly DbContext _dbContext;
    
        public CustomClaimsTransformation(DbContext dbContext)
        {
            _dbContext = dbContext;
        }
        
        public async Task<ClaimsPrincipal> TransformAsync(ClaimsPrincipal principal)
        {       
            var customRoleClaims = new List<Claim>();
        
            // insert here logic to determine custom claims. 
            // e.g. does the user have some role that we determine 
            // manually, using the database etc
            principal.AddIdentity(new ClaimsIdentity(customRoleClaims, JwtBearerDefaults.AuthenticationScheme, null, "roles"));
        }
    }
    

    Register this in Program.cs:

    services.AddTransient<IClaimsTransformation, CustomClaimsTransformation>();
    

    Here is a link to Microsoft's documentation for more detail: https://learn.microsoft.com/en-us/aspnet/core/security/authentication/claims?view=aspnetcore-8.0#extend-or-add-custom-claims-using-iclaimstransformation