Enrich Token Claims with ASP.NET Core

Enrich Token Claims with ASP.NET Core

Enrich Token Claims with ASP.NET Core

Often you have the requirement that you need or want to add additional claims to a token - either the, ID token or the access token. This is especially useful when one needs an additional custom enrichment that is not available at the time of token creation.

ASP.NET Core has a corresponding interface in the Auth pipeline for this purpose: the IClaimsTransformation.

All implementations of this interface are instantiated automatically if they have been registered.

services.AddScoped<IClaimsTransformation, AddCustomClaimsToIdentityTransformation>();

All implementations are run through in the order in which they were registered.

The implementation itself is very simple:

public class AddCustomClaimsToIdentityTransformation : IClaimsTransformation
{
    public async Task<ClaimsPrincipal> TransformAsync(ClaimsPrincipal principal)
    {
        ClaimsPrincipal clone = principal.Clone();
        ClaimsIdentity newIdentity = (ClaimsIdentity)clone.Identity;

        // support aad / ad / others, too
        Claim? nameId = principal.Claims
            .FirstOrDefault(c => c.Type == ClaimTypes.NameIdentifier || c.Type == ClaimTypes.Name);
        if (nameId is null) return principal;

        // request data from your claim source
        var myClaimData = await _myRepository.GetAdditionClaimsOfUser(nameId).ConfigureAwait(false);
        foreach (var customClaim in myClaimData)
        {  
            newIdentity.AddClaim(new(customClaim.Type, customClaim.Value));
        }

        return clone;
    }
}