
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.
1services.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

Feb 09, 2022 - 1 min read
ASP.NET Core 7 Roadmap veröffentlicht
Das Microsoft ASP.NET Team hat nun die Roadmap zu .NET 7 veröffentlicht. Der Release ist für November 2022 geplant. Der GitHub Link: ASP.NET …

Jun 18, 2021 - 2 min read
Parse HTTP User Agents with ASP.NET Core
In my last blog post I shared why we wrote our own user agent parser (mycsharp/HttpUserAgentParser ) in .NET (reason: performance).

May 18, 2020 - 2 min read
Build and Test .NET Core with GitHub Actions
What is GitHub Actions? GitHub Actions is the counterpart to Azure DevOps Pipelines: a fully configurable automation tool for setting up …
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.
