Claims and roles in ASP.NET Core: ClaimsPrincipal and ClaimsIdentity, NameClaimType and RoleClaimType, inbound claim mapping, IClaimsTransformation, and sourcing permissions from tokens vs the application.
A claim is a type/value statement about the user made by an issuer, such as sub=42 or roles=Admin. A ClaimsPrincipal holds one or more ClaimsIdentity objects; each identity's NameClaimType and RoleClaimType decide what User.Identity.Name and User.IsInRole read, so a role is just a claim.
The JWT and OIDC handlers map inbound claims by default (sub becomes ClaimTypes.NameIdentifier); MapInboundClaims = false keeps the issuer's names. IClaimsTransformation can add application claims after authentication, but it runs on every authenticate call, so it must be idempotent and cached.
Permissions: take identity and coarse roles from the identity provider, and fine-grained, app-specific permissions from your own store. The trade-off is token size and staleness versus a lookup per request.
"A claim is a statement about the subject, issued by someone you trust: a type, a value and an issuer. The identity provider puts claims in the token, the authentication handler turns them into a
ClaimsIdentity, and theClaimsPrincipalonHttpContext.Useris the collection of identities. Roles aren't a separate concept:IsInRolesimply looks for claims of the identity'sRoleClaimType, and[Authorize(Roles = \"Admin\")]uses the same thing.The surprise for most people is claim mapping. By default the JWT bearer and OpenID Connect handlers rename short JWT claim names to the long WS-Federation URIs, so
subshows up ashttp://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier. If you setMapInboundClaims = falseyou getsub,rolesandscpas issued, which is easier to reason about, but then you must setNameClaimTypeandRoleClaimTypeorIdentity.Nameis null and role checks stop matching. When the token doesn't carry what the app needs,IClaimsTransformationlets you add claims, for example the user's tenant or their permissions from the database. It runs every time the principal is authenticated, which can be more than once per request, so it has to be idempotent and should hit a cache, not the database every time.The mistake I see is pushing every permission into the token or cookie, until it's 8 KB and stale for an hour. The senior line: the identity provider knows who the user is; the application knows what they may do in it."
| Concept | API | Note |
|---|---|---|
| Claim | Claim(type, value, valueType, issuer) |
Immutable statement |
| Identity | ClaimsIdentity(claims, authenticationType, nameType, roleType) |
IsAuthenticated is true when authenticationType is set |
| Principal | ClaimsPrincipal |
HttpContext.User; can hold several identities |
| Name | Identity.Name |
Reads NameClaimType |
| Roles | IsInRole, RequireRole |
Read RoleClaimType |
| Source | Good for | Weakness |
|---|---|---|
| IdP token (roles, groups, scopes) | Coarse roles, app roles, delegated scopes | Stale until token refresh; size limits; IdP admins own it |
| App database via claims transformation | Fine-grained, per-tenant, per-resource permissions | Lookup cost; needs caching and invalidation |
| Resource-based checks at runtime | Ownership ('only the author may edit') | Can't be expressed as claims at all |
| Claim | Meaning |
|---|---|
oid |
Stable user object id in the tenant (use this, not email, as the key) |
tid |
Tenant id |
scp |
Space-separated delegated scopes |
roles |
App roles (users or applications) |
groups |
Group ids; above 200 groups in a JWT you get an overage claim instead |
At [company], a [B2B] app put all [~150] permissions into the cookie as claims, hitting 3 chunked cookies and [~9 KB] per request. Moving permissions to a claims transformation backed by a 5-minute HybridCache entry cut the cookie to [~1 KB] and made permission changes take effect in minutes instead of at next sign-in.
Checks that the candidate understands claims as the data model of identity in .NET and makes sensible choices about where permission data comes from.
Green flags
NameClaimType / RoleClaimType and claim mappingIClaimsTransformation runs repeatedly and must be idempotentoid, scp, rolesRed flags
JWT payload {sub, name, roles:["Admin"], scp:"Orders.Read"}
-> JsonWebTokenHandler validates
-> claim mapping (if MapInboundClaims) : sub -> ...nameidentifier, roles -> ...role
-> ClaimsIdentity(authenticationType: "AuthenticationTypes.Federation",
nameType: options.NameClaimType, roleType: options.RoleClaimType)
-> AuthenticateResult -> HttpContext.User
-> IClaimsTransformation.TransformAsync(principal) (if registered)
The mapping table lives in JsonWebTokenHandler.DefaultInboundClaimTypeMap (and the older JwtSecurityTokenHandler.DefaultInboundClaimTypeMap). Setting the option per scheme is cleaner than clearing the global map.
IClaimsTransformation is called by AuthenticationService.AuthenticateAsync. Anything that calls authenticate, including the middleware, authorisation and some handlers, triggers it, so:
HybridCache or IMemoryCache) and accept a short staleness window.DbContext.Roles describe people (Clerk, Manager); permissions describe actions (invoice.approve). Mapping roles to permissions inside the app means a new role doesn't require code changes, and policies check permissions. That is the subject of permission-based authorisation, but the claims layer is where the data arrives.
Cookies over ~4 KB are chunked; headers over Kestrel's 32 KB request header limit fail with 431. Tokens carry claims until they expire, so a revoked role lingers for the access token lifetime. Group claims in Entra ID overflow at 200 groups in a JWT, replaced by a _claim_names / hasgroups indicator that tells you to query Microsoft Graph.
User.Claims for a JWT with and without MapInboundClaims and compare the types.MapInboundClaims = false without changing RoleClaimType and watch a [Authorize(Roles = ...)] endpoint return 403.IClaimsTransformation that logs each call; count how many times it runs per request.HybridCache to the transformation and measure database calls under a k6 load test.Keeping issued claim names, then adding application permissions with a cached, idempotent claims transformation.
// Program.cs (.NET 10)
using System.Security.Claims;
using Microsoft.AspNetCore.Authentication;
using Microsoft.Extensions.Caching.Hybrid;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddAuthentication().AddJwtBearer(o =>
{
o.Authority = builder.Configuration["Auth:Authority"];
o.Audience = builder.Configuration["Auth:Audience"];
o.MapInboundClaims = false; // keep 'sub', 'roles', 'scp'
o.TokenValidationParameters.NameClaimType = "name";
o.TokenValidationParameters.RoleClaimType = "roles";
});
builder.Services.AddHybridCache();
builder.Services.AddScoped<IPermissionStore, SqlPermissionStore>();
builder.Services.AddScoped<IClaimsTransformation, PermissionClaimsTransformation>();
builder.Services.AddAuthorization();
var app = builder.Build();
app.UseAuthentication();
app.UseAuthorization();
app.MapGet("/invoices/approve", () => Results.Ok())
.RequireAuthorization(p => p.RequireClaim("perm", "invoice.approve"));
app.Run();
public interface IPermissionStore
{
Task<string[]> GetPermissionsAsync(string userId, CancellationToken ct);
}
public sealed class SqlPermissionStore : IPermissionStore
{
// Real code would query role -> permission tables with EF Core.
public Task<string[]> GetPermissionsAsync(string userId, CancellationToken ct) =>
Task.FromResult<string[]>(["invoice.read", "invoice.approve"]);
}
public sealed class PermissionClaimsTransformation(IPermissionStore store, HybridCache cache) : IClaimsTransformation
{
private const string AppIdentity = "app-permissions";
public async Task<ClaimsPrincipal> TransformAsync(ClaimsPrincipal principal)
{
// Idempotent: this can run several times per request.
if (principal.Identities.Any(i => i.AuthenticationType == AppIdentity))
return principal;
var userId = principal.FindFirstValue("sub");
if (userId is null) return principal;
var permissions = await cache.GetOrCreateAsync(
$"perms:{userId}",
async ct => await store.GetPermissionsAsync(userId, ct),
new HybridCacheEntryOptions { Expiration = TimeSpan.FromMinutes(5) });
var clone = principal.Clone(); // don't mutate the original
clone.AddIdentity(new ClaimsIdentity(permissions.Select(p => new Claim("perm", p)), AppIdentity));
return clone;
}
}
MapInboundClaims = false without setting NameClaimType and RoleClaimType. Why it is wrong: Identity.Name becomes null and role checks quietly fail. Instead: configure both whenever you change mapping.email or name as the user key. Why it is wrong: they change and aren't unique across tenants or IdPs. Instead: sub, or oid + tid in Entra ID.IClaimsTransformation on every call. Why it is wrong: it runs several times per request and multiplies database load. Instead: make it idempotent and cache per user.role from a registration form. Why it is wrong: privilege escalation. Instead: only trust claims from your IdP or your own store.roles but no scp; a user token may have both meanings. Instead: separate policies for delegated (scp) and application (roles) access.Claims are inputs, not decisions. A senior design keeps the token small and stable (who the user is, which tenant, coarse roles), adds app-specific permissions in one cached place, and makes policies the only place that interprets them. The staleness window is a business decision: say it out loud ('a revoked permission lasts up to 5 minutes') and pick cache and token lifetimes to match.
| Option | When it fits | Cost | When not to |
|---|---|---|---|
| Roles in the IdP token | A few stable roles, admins manage them in Entra | Stale until token refresh | Per-tenant or per-resource permissions |
| Claims transformation + cache | Fine-grained app permissions | Cache, invalidation, one lookup per user per window | When permissions are needed in other services too (consider a permission service) |
| Permissions in a custom token from your own STS | Many services need the same permissions | Token size, issuing infrastructure | Small apps |
Measure cookie and header sizes, transformation call counts per request, and cache hit rate.
A JWT is three base64url parts, header.payload.signature. The header says which algorithm and key (alg, kid) signed it; the payload holds claims (iss, aud, sub, exp, scopes); the signature proves nobody changed them. It is signed, not encrypted, so anyone holding it can read it: no personal or secret data.
AddJwtBearer with Authority and Audience validates issuer, audience, lifetime and signature (with a 5-minute ClockSkew).The trade-off: validation is local and fast, but a stolen token is valid until exp, so keep access tokens short-lived.
Entra ID limits how many group ids it puts in a token: above 200 groups in a JWT (150 for SAML, 6 for implicit flow) it omits the groups claim and adds an overage indicator (_claim_names / _claim_sources pointing at Microsoft Graph, or hasgroups in some flows), so the app must call Graph (/me/getMemberObjects or /users/{id}/transitiveMemberOf) to get memberships, which needs a Graph permission, adds latency and should be cached. Better designs avoid raw groups: define app roles and assign them to groups, so the token carries a short roles list; or set the group claim to 'groups assigned to the application' only; or keep fine-grained permissions in the app and cache them. Code must handle the overage case explicitly, or users silently lose access.
Last updated 23 Nov 2026.