
This article was written in 2022. Versions, tools and recommendations may have changed since then. Newer posts are collected under 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:
1public class AddCustomClaimsToIdentityTransformation : IClaimsTransformation
2{
3 public async Task<ClaimsPrincipal> TransformAsync(ClaimsPrincipal principal)
4 {
5 ClaimsPrincipal clone = principal.Clone();
6 ClaimsIdentity newIdentity = (ClaimsIdentity)clone.Identity;
7
8 // support aad / ad / others, too
9 Claim? nameId = principal.Claims
10 .FirstOrDefault(c => c.Type == ClaimTypes.NameIdentifier || c.Type == ClaimTypes.Name);
11 if (nameId is null) return principal;
12
13 // request data from your claim source
14 var myClaimData = await _myRepository.GetAdditionClaimsOfUser(nameId).ConfigureAwait(false);
15 foreach (var customClaim in myClaimData)
16 {
17 newIdentity.AddClaim(new(customClaim.Type, customClaim.Value));
18 }
19
20 return clone;
21 }
22}Related articles

- 12 min read
Problem Details in ASP.NET Core and .NET 11
builder.Services.AddProblemDetails() registers infrastructure. It does not create an error contract. An ASP.NET Core request can fail during …

- 11 min read
Resilience in .NET with Microsoft.Extensions.Resilience
Retries are the most visible resilience strategy and the easiest one to misuse. Repeating a failing call can recover from a short network …

- 10 min read
What Matters in ASP.NET Core 11
ASP.NET Core 11 has no single feature that fundamentally changes how web applications are built. That is not a criticism. Mature frameworks …
Let's Work Together
Looking for an experienced Platform Architect or Engineer for your next project? Whether it's cloud migration, platform modernization or building new solutions from scratch - I'm here to help you succeed.
