Mapping, customizing, and transforming claims in ASP.NET Core (2024)

  • Article
  • 7 minutes to read

By Damien Bowden

Claims can be created from any user or identity data which can be issued using a trusted identity provider or ASP.NET Core identity. A claim is a name value pair that represents what the subject is, not what the subject can do.This article covers the following areas:

  • How to configure and map claims using an OpenID Connect client
  • Set the name and role claim
  • Reset the claims namespaces
  • Customize, extend the claims using TransformAsync

Mapping claims using OpenID Connect authentication

The profile claims can be returned in the id_token, which is returned after a successful authentication. The ASP.NET Core client app only requires the profile scope. When using the id_token for claims, no extra claims mapping is required.

using Microsoft.AspNetCore.Authentication.Cookies;using Microsoft.AspNetCore.Authentication.OpenIdConnect;var builder = WebApplication.CreateBuilder(args);builder.Services.AddRazorPages();builder.Services.AddAuthentication(options =>{ options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme; options.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme;}) .AddCookie() .AddOpenIdConnect(options => { options.SignInScheme = "Cookies"; options.Authority = "-your-identity-provider-"; options.RequireHttpsMetadata = true; options.ClientId = "-your-clientid-"; options.ClientSecret = "-your-client-secret-from-user-secrets-or-keyvault"; options.ResponseType = "code"; options.UsePkce = true; options.Scope.Add("profile"); options.SaveTokens = true; });var app = builder.Build();if (!app.Environment.IsDevelopment()){ app.UseExceptionHandler("/Error"); app.UseHsts();}app.UseHttpsRedirection();app.UseStaticFiles();app.UseAuthentication();app.UseAuthorization();app.MapRazorPages();app.Run();

The preceding code requires the Microsoft.AspNetCore.Authentication.OpenIdConnect NuGet package.

Another way to get the user claims is to use the OpenID Connect User Info API. The ASP.NET Core client app uses the GetClaimsFromUserInfoEndpoint property to configure this. One important difference from the first settings, is that you must specify the claims you require using the MapUniqueJsonKey method, otherwise only the name, given_name and email standard claims will be available in the client app. The claims included in the id_token are mapped per default. This is the major difference to the first option. You must explicitly define some of the claims you require.

using Microsoft.AspNetCore.Authentication;using Microsoft.AspNetCore.Authentication.Cookies;using Microsoft.AspNetCore.Authentication.OpenIdConnect;var builder = WebApplication.CreateBuilder(args);builder.Services.AddRazorPages();builder.Services.AddAuthentication(options =>{ options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme; options.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme;}) .AddCookie() .AddOpenIdConnect(options => { options.SignInScheme = "Cookies"; options.Authority = "-your-identity-provider-"; options.RequireHttpsMetadata = true; options.ClientId = "-your-clientid-"; options.ClientSecret = "-client-secret-from-user-secrets-or-keyvault"; options.ResponseType = "code"; options.UsePkce = true; options.Scope.Add("profile"); options.SaveTokens = true; options.GetClaimsFromUserInfoEndpoint = true; options.ClaimActions.MapUniqueJsonKey("preferred_username", "preferred_username"); options.ClaimActions.MapUniqueJsonKey("gender", "gender"); });var app = builder.Build();// Code removed for brevity.

Name claim and role claim mapping

The Name claim and the Role claim are mapped to default properties in the ASP.NET Core HTTP context. Sometimes it is required to use different claims for the default properties, or the name claim and the role claim do not match the default values. The claims can be mapped using the TokenValidationParameters property and set to any claim as required. The values from the claims can be used directly in the HttpContext User.Identity.Name property and the roles.

If the User.Identity.Name has no value or the roles are missing, please check the values in the returned claims and set the NameClaimType and the RoleClaimType values. The returned claims from the client authentication can be viewed in the HTTP context.

builder.Services.AddAuthentication(options =>{ options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme; options.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme;}) .AddCookie() .AddOpenIdConnect(options => { // Other options... options.TokenValidationParameters = new TokenValidationParameters { NameClaimType = "email" //, RoleClaimType = "role" }; });

Claims namespaces, default namespaces

ASP.NET Core adds default namespaces to some known claims, which might not be required in the app. Optionally, disable these added namespaces and use the exact claims that the OpenID Connect server created.

var builder = WebApplication.CreateBuilder(args);builder.Services.AddRazorPages();JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear();builder.Services.AddAuthentication(options =>{ options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme; options.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme;}) .AddCookie() .AddOpenIdConnect(options => { options.SignInScheme = "Cookies"; options.Authority = "-your-identity-provider-"; options.RequireHttpsMetadata = true; options.ClientId = "-your-clientid-"; options.ClientSecret = "-your-client-secret-from-user-secrets-or-keyvault"; options.ResponseType = "code"; options.UsePkce = true; options.Scope.Add("profile"); options.SaveTokens = true; });var app = builder.Build();// Code removed for brevity.

Extend or add custom claims using IClaimsTransformation

The IClaimsTransformation interface can be used to add extra claims to the ClaimsPrincipal class. The interface requires a single method TransformAsync. This method might get called multiple times. Only add a new claim if it does not already exist in the ClaimsPrincipal. A ClaimsIdentity is created to add the new claims and this can be added to the ClaimsPrincipal.

using Microsoft.AspNetCore.Authentication;using System.Security.Claims;public class MyClaimsTransformation : IClaimsTransformation{ public Task<ClaimsPrincipal> TransformAsync(ClaimsPrincipal principal) { ClaimsIdentity claimsIdentity = new ClaimsIdentity(); var claimType = "myNewClaim"; if (!principal.HasClaim(claim => claim.Type == claimType)) { claimsIdentity.AddClaim(new Claim(claimType, "myClaimValue")); } principal.AddIdentity(claimsIdentity); return Task.FromResult(principal); }}

The IClaimsTransformation interface and the MyClaimsTransformation class can be registered as a service:

builder.Services.AddTransient<IClaimsTransformation, MyClaimsTransformation>();

Map claims from external identity providers

Refer to the following document:

Persist additional claims and tokens from external providers in ASP.NET Core

Claims can be created from any user or identity data which can be issued using a trusted identity provider or ASP.NET Core identity. A claim is a name value pair that represents what the subject is, not what the subject can do.This article covers the following areas:

  • How to configure and map claims using an OpenID Connect client
  • Set the name and role claim
  • Reset the claims namespaces
  • Customize, extend the claims using TransformAsync

Mapping claims using OpenID Connect authentication

The profile claims can be returned in the id_token, which is returned after a successful authentication. The ASP.NET Core client app only requires the profile scope. When using the id_token for claims, no extra claims mapping is required.

public void ConfigureServices(IServiceCollection services){ services.AddAuthentication(options => { options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme; options.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme; }) .AddCookie() .AddOpenIdConnect(options => { options.SignInScheme = "Cookies"; options.Authority = "-your-identity-provider-"; options.RequireHttpsMetadata = true; options.ClientId = "-your-clientid-"; options.ClientSecret = "-your-client-secret-from-user-secrets-or-keyvault"; options.ResponseType = "code"; options.UsePkce = true; options.Scope.Add("profile"); options.SaveTokens = true; });

Another way to get the user claims is to use the OpenID Connect User Info API. The ASP.NET Core client application uses the GetClaimsFromUserInfoEndpoint property to configure this. One important difference from the first settings, is that you must specify the claims you require using the MapUniqueJsonKey method, otherwise only the name, given_name and email standard claims will be available in the client application. The claims included in the id_token are mapped per default. This is the major difference to the first option. You must explicitly define some of the claims you require.

public void ConfigureServices(IServiceCollection services){ services.AddAuthentication(options => { options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme; options.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme; }) .AddCookie() .AddOpenIdConnect(options => { options.SignInScheme = "Cookies"; options.Authority = "-your-identity-provider-"; options.RequireHttpsMetadata = true; options.ClientId = "-your-clientid-"; options.ClientSecret = "-your-client-secret-from-user-secrets-or-keyvault"; options.ResponseType = "code"; options.UsePkce = true; options.Scope.Add("profile"); options.SaveTokens = true; options.GetClaimsFromUserInfoEndpoint = true; options.ClaimActions.MapUniqueJsonKey("preferred_username", "preferred_username"); options.ClaimActions.MapUniqueJsonKey("gender", "gender"); }); 

Name claim and role claim mapping

The Name claim and the Role claim are mapped to default properties in the ASP.NET Core HTTP context. Sometimes it is required to use different claims for the default properties, or the name claim and the role claim do not match the default values. The claims can be mapped using the TokenValidationParameters property and set to any claim as required. The values from the claims can be used directly in the HttpContext User.Identity.Name property and the roles.

If the User.Identity.Name has no value or the roles are missing, please check the values in the returned claims and set the NameClaimType and the RoleClaimType values. The returned claims from the client authentication can be viewed in the HTTP context.

public void ConfigureServices(IServiceCollection services){ services.AddAuthentication(options => { options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme; options.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme; }) .AddCookie() .AddOpenIdConnect(options => { // other options... options.TokenValidationParameters = new TokenValidationParameters { NameClaimType = "email", // RoleClaimType = "role" }; });

Claims namespaces, default namespaces

ASP.NET Core adds default namespaces to some known claims, which might not be required in the app. Optionally, disable these added namespaces and use the exact claims that the OpenID Connect server created.

public void Configure(IApplicationBuilder app){ JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear();

Extend or add custom claims using IClaimsTransformation

The IClaimsTransformation interface can be used to add extra claims to the ClaimsPrincipal class. The interface requires a single method TransformAsync. This method might get called multiple times. Only add a new claim if it does not already exist in the ClaimsPrincipal. A ClaimsIdentity is created to add the new claims and this can be added to the ClaimsPrincipal.

public class MyClaimsTransformation : IClaimsTransformation{ public Task<ClaimsPrincipal> TransformAsync(ClaimsPrincipal principal) { ClaimsIdentity claimsIdentity = new ClaimsIdentity(); var claimType = "myNewClaim"; if (!principal.HasClaim(claim => claim.Type == claimType)) { claimsIdentity.AddClaim(new Claim(claimType, "myClaimValue")); } principal.AddIdentity(claimsIdentity); return Task.FromResult(principal); }}

The IClaimsTransformation interface and the MyClaimsTransformation class can be added in the ConfigureServices method as a service.

public void ConfigureServices(IServiceCollection services){ services.AddTransient<IClaimsTransformation, MyClaimsTransformation>();

Extend or add custom claims in ASP.NET Core Identity

Refer to the following document:

Add claims to Identity using IUserClaimsPrincipalFactory

Map claims from external identity providers

Refer to the following document:

Persist additional claims and tokens from external providers in ASP.NET Core

Mapping, customizing, and transforming claims in ASP.NET Core (2024)

FAQs

How to implement claims-based authentication in .NET core? ›

I have achieved this by using the following code. Claim-based authorization can be done by creating policy; i.e., create and register policy stating the claims requirement. The simple type of claim policy checks only for the existence of the claim but with advanced level, we can check the user claim with its value.

What is ClaimsIdentity in ASP.NET Core? ›

The ClaimsIdentity class is a concrete implementation of a claims-based identity; that is, an identity described by a collection of claims. A claim is a statement about an entity made by an issuer that describes a property, right, or some other quality of that entity.

How do I override Authorize attribute in .NET core? ›

Right-click on the solution and add a new class. Enter the class name and click on Add. Next Inherite Attribute, IAuthorizationFilter to CustomAuthorization class which has overridden the OnAuthorization method. The OnAuthorization Method has the AuthorizationFilterContext parameter.

What is the major difference between authentication and authorization? ›

Authentication verifies the identity of a user or service, and authorization determines their access rights. Although the two terms sound alike, they play separate but equally essential roles in securing applications and data. Understanding the difference is crucial. Combined, they determine the security of a system.

How claims work in ASP.NET Core? ›

Claim based authorization checks are declarative - the developer embeds them within their code, against a controller or an action within a controller, specifying claims which the current user must possess, and optionally the value the claim must hold to access the requested resource.

What are claims in Active Directory? ›

In its simplest form, claims are simply statements (for example, name, identity, group), made about users, that are used primarily for authorizing access to claims-based applications located anywhere on the Internet. Each statement corresponds to a value that is stored in the claim.

How does ClaimsIdentity work? ›

By default, ClaimsIdentity gets that Name property value from a claim with the claim type of ClaimTypes.Name. If you didn't set that value or you didn't set that value properly in the list of Claims you passed in, then that Name property won't get set.

How many types of authorization are there in ASP.NET Core? ›

There are two ways in which you can implement authorization in ASP.NET Core. These include role-based authorization and policy-based authorization.

When should we use Authorize attribute? ›

This attribute is useful when you want to use the Authorize attribute on a controller to protect all of the actions inside, but then there is this single action or one or two actions that you want to unprotect and allow anonymous users to reach that specific action.

Which is the controller method to override authorization filters? ›

In similar way if we want to override Result filter or Exception filter then we need to apply [OverrideResultFilters] or [OverrideExceptionFilters] on the Action Method where you need to Override.

What are the four main functions recognized in processing a claim? ›

In essence, claims processing refers to the insurance company's procedure to check the claim requests for adequate information, validation, justification and authenticity.

How can claim errors be prevented? ›

Errors or omissions are a common cause of claim denials and can be easily prevented by double-checking all fields before submitting a claim. Incorrect or missing patient names, addresses, birth dates, insurance information, sex, dates of treatment and onset can all cause problems.

What are the three 3 main types of authentication? ›

Authentication factors can be classified into three groups: something you know: a password or personal identification number (PIN); something you have: a token, such as bank card; something you are: biometrics, such as fingerprints and voice recognition.

What are those 4 commonly authentication methods *? ›

Common biometric authentication methods include fingerprint identification, voice recognition, retinal and iris scans, and face scanning and recognition.

What are the four commonly authentication methods? ›

The most common authentication methods are Password Authentication Protocol (PAP), Authentication Token, Symmetric-Key Authentication, and Biometric Authentication.

What are the 4 factors of authentication? ›

Four-factor authentication (4FA) is the use of four types of identity-confirming credentials, typically categorized as knowledge, possession, inherence and location factors.

Why is claims so important? ›

Paying a claim is an essential part of the insurance value proposition; it's a critical component of the promise that insurers make to their policyholders – to cover them in the case of a loss. The insurance claims experience, then, becomes a pivotal moment for insurers and policyholders alike.

How do you calculate percentage of claims? ›

How is health insurance claim ratio calculated? Hence, the number of claims accepted is simply divided by the total number of received in the same time period, and this number is ascribed a percentage value.

What is claims in JSON? ›

A claim is represented as a name-value pair that contains a Claim Name and a Claim Value. The claims in a JWT are encoded as a JSON object that is used as the payload of a JSON Web Signature (JWS) structure or as the plain-text of a JSON Web Encryption (JWE) structure.

What are claims in Identity server? ›

Claims are pieces of information about a user that have been packaged, signed into security tokens and sent by an issuer or identity provider to relying party applications through a security token service (STS).

How many types of claims are there? ›

The six most common types of claim are: fact, definition, value, cause, comparison, and policy.

What is claim mapping? ›

A claims mapping policy is a type of Policy object that modifies the claims emitted in tokens issued for specific applications.

What is claim tracking? ›

Tracking claims gives you a definite advantage in terms of projecting or anticipating revenue vs. guessing as to what will be paid. You're able to contact the payer if you see claims idling and question the payer as to their status.

What is claims JWT? ›

JSON web tokens (JWTs) claims are pieces of information asserted about a subject. For example, an ID token (which is always a JWT ) can contain a claim called name that asserts that the name of the user authenticating is "John Doe".

What is claim principal identity? ›

ClaimsPrincipal exposes a collection of identities, each of which is a ClaimsIdentity. In the common case, this collection, which is accessed through the Identities property, will only have a single element. The introduction of ClaimsPrincipal in .

What is claim based access control? ›

CBAC is an access control paradigm that uses the claims to make access-control decisions to resources. In Windows, CBAC is built on the conditional ACEs feature, not only to use the user claims, but also to use the resource claims, which are referred to as resource properties, in order to make access control decisions.

What is difference between authentication and authorization in ASP.NET Core? ›

Authentication is the process of determining a user's identity. Authorization is the process of determining whether a user has access to a resource. In ASP.NET Core, authentication is handled by the authentication service, IAuthenticationService, which is used by authentication middleware.

What is the difference between Authorize and Authorize and capture? ›

What is the difference between the Authorize Only and Authorize and Capture payment actions? Authorize only will check the card for validity but not charge the account until the order is approved and invoiced. Authorize and capture will charge the debit/credit card at the time of the order submission.

Should authorization be in the controller or service? ›

Authorization should neither be part of controller or domain model. Instead it should be in the service layer. Controller should just act as dispatcher and delegate between HTTP and application service. It's the application service where the orchestration takes place.

What is claim editing? ›

Claim editing, one of many cost containment solutions, occurs during the healthcare reimbursement process to ensure the accuracy of items listed on a medical bill. This protects the patient from overpaying for services or paying for things that should not have been billed in the first place.

What is a claim reference value? ›

Claim of Value: Makes a judgment by expressing approval or disapproval, attempting to prove that some action, belief or condition is right or wrong, good or bad, beautiful or ugly, worthwhile or undesirable. Value claims about morality express judgments about the rightness or wrongness of conduct or belief.

What is claim status code 252? ›

252 An attachment is required to adjudicate this claim/service. At least one Remark Code must be provided (may be comprised of either the NCPDP Reject Reason Code, or Remittance Advice Remark Code that is not an ALERT).

What is claim transformation? ›

The claims transformation adds the salt to the email address before hashing the value. To call this claims transformation, set a value to the mySalt claim.

Top Articles
Latest Posts
Article information

Author: Allyn Kozey

Last Updated:

Views: 6190

Rating: 4.2 / 5 (63 voted)

Reviews: 86% of readers found this page helpful

Author information

Name: Allyn Kozey

Birthday: 1993-12-21

Address: Suite 454 40343 Larson Union, Port Melia, TX 16164

Phone: +2456904400762

Job: Investor Administrator

Hobby: Sketching, Puzzles, Pet, Mountaineering, Skydiving, Dowsing, Sports

Introduction: My name is Allyn Kozey, I am a outstanding, colorful, adventurous, encouraging, zealous, tender, helpful person who loves writing and wants to share my knowledge and understanding with you.