In ASP.NET Core's JwtBearer handler, why does User.FindFirst("sub") return null for a token that has a sub claim, and what changes with MapInboundClaims = false?
answer
- claim types are renamed on the way in
- MapInboundClaims defaults to true
- sub becomes ClaimTypes.NameIdentifier
- name is not mapped; NameClaimType is
- JsonWebTokenHandler has its own map since 8
basics
~10 sJwtBearerOptions.MapInboundClaims defaults to true, so short JWT claim names are renamed to long ClaimTypes URIs: sub becomes ClaimTypes.NameIdentifier. Setting it to false keeps the JWT names, and then NameClaimType and RoleClaimType must name them.
solid answer
~30 s`JwtBearerOptions.MapInboundClaims` defaults to `true`, and the token handler then renames claim types through an inbound map: `sub` becomes `ClaimTypes.NameIdentifier`, `email` becomes `ClaimTypes.Email`, `role` and `roles` become `ClaimTypes.Role`, `unique_name` becomes `ClaimTypes.Name`. So `FindFirst("sub")` finds nothing. `name` is not in the map, so `User.Identity.Name` stays null for a provider that sends `name`, because `NameClaimType` defaults to `ClaimTypes.Name`. With `MapInboundClaims = false` every claim keeps its JWT name; then set `TokenValidationParameters.NameClaimType = "name"` and `RoleClaimType` to the provider's role claim, or `[Authorize(Roles = ...)]` and `IsInRole` stop matching. Since ASP.NET Core 8 the handler validates with `JsonWebTokenHandler`, so clearing `JwtSecurityTokenHandler.DefaultInboundClaimTypeMap` no longer changes anything.
code
csharp · 7 linesapp.MapGet("/accounts/me", (ClaimsPrincipal user) =>
{
// MapInboundClaims = true (default): sub arrives as NameIdentifier
var customerId = user.FindFirstValue(ClaimTypes.NameIdentifier);
var raw = user.FindFirstValue("sub"); // null with the default mapping
return Results.Ok(new { customerId, raw });
}).RequireAuthorization();go deeper
Remember that the handler renames claims by default, so the subject id is under ClaimTypes.NameIdentifier rather than sub.
Explain the inbound map, why Identity.Name can be null, and the NameClaimType and RoleClaimType settings that MapInboundClaims = false requires.
Know the ASP.NET Core 8 switch to JsonWebTokenHandler: the old static map no longer applies, and SecurityToken in events is a JsonWebToken.
Set one claim-type convention for every API and handler in the estate, so authorization rules and logs agree across services.
## Two vocabularies for the same claim A JWT names its claims with short strings: `sub` (subject), `email`, `role`, `name`. .NET's `ClaimTypes` class predates JWTs and uses long URIs such as `http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier`. For compatibility with code written against `ClaimTypes`, the token handlers can **translate inbound claim types** from the short form to the long one. `JwtBearerOptions.MapInboundClaims` decides whether that happens, and **its default is `true`** (it starts from `JwtSecurityTokenHandler.DefaultMapInboundClaims`, which is `true`, and pushes the value into the `JsonWebTokenHandler` it creates). The standalone `JsonWebTokenHandler` defaults to `false`, which is why code that validates a token by hand sees different claim types from the API. | JWT claim | Claim type on `HttpContext.User` with mapping on | |---|---| | `sub` | `ClaimTypes.NameIdentifier` | | `email` | `ClaimTypes.Email` | | `role`, `roles` | `ClaimTypes.Role` | | `unique_name` | `ClaimTypes.Name` | | `scp` | `http://schemas.microsoft.com/identity/claims/scope` | | `name` | `name` (not in the map) | ## The symptoms - `User.FindFirst("sub")` is null while `User.FindFirst(ClaimTypes.NameIdentifier)` holds the customer id. - `User.Identity.Name` is null for a provider that sends `name`: the identity's `NameClaimType` comes from `TokenValidationParameters.NameClaimType`, which defaults to `ClaimTypes.Name`, and `name` is not mapped to it. - Code that reads `"email"` or `"role"` finds nothing. ## Turning mapping off Many teams prefer the claim names the provider documents: ```csharp builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) .AddJwtBearer(options => { options.Authority = "https://id.example.com/"; options.Audience = "mobile-banking-api"; options.MapInboundClaims = false; options.TokenValidationParameters.NameClaimType = "name"; options.TokenValidationParameters.RoleClaimType = "role"; }); ``` The last two lines are the part people forget. With mapping off, the role claim arrives as `role`, but `RoleClaimType` still defaults to `ClaimTypes.Role`, so `IsInRole("teller")` and `[Authorize(Roles = "teller")]` match nothing. Check which claim your provider actually uses for roles; some send `roles`. ## The ASP.NET Core 8 change Before 8, `JwtBearer` validated with `JwtSecurityTokenHandler`, and a common way to stop renaming was to clear its static map at startup: - `JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear()` Since **ASP.NET Core 8**, the handler validates through `TokenHandlers`, whose default entry is a `JsonWebTokenHandler`. That handler copies its inbound map from **`JsonWebTokenHandler.DefaultInboundClaimTypeMap`**, so clearing the old static no longer affects `JwtBearer`. The supported switch is `MapInboundClaims`, which the options setter applies to the handler instances it owns. The same release changed the token type handed to events: `TokenValidatedContext.SecurityToken` is now a `JsonWebToken` rather than a `JwtSecurityToken`, unless you opt back into the obsolete validators with `UseSecurityTokenValidators = true`. ## Choosing 1. **Mapping on (default)**: code uses `ClaimTypes.*` constants; fine for apps mixing several authentication sources that already speak that vocabulary. 2. **Mapping off**: claim names match the provider's documentation and the token you inspect; set `NameClaimType` and `RoleClaimType` explicitly. Whichever you choose, choose it once for the whole API; code that reads `"sub"` in one place and `ClaimTypes.NameIdentifier` in another breaks the day someone flips the switch. If an app needs extra claims from a database, that is a claims transformation step, separate from this renaming. ## Checking what actually arrived When a claim seems to be missing, list what the handler produced rather than guessing: - Return `user.Claims.Select(c => new { c.Type, c.Value })` from a development-only endpoint and compare it with the decoded token. - Look at `user.Identity` as a `ClaimsIdentity`: its `NameClaimType` and `RoleClaimType` show which types `Identity.Name` and `IsInRole` consult. - Remember that two handlers can disagree: a hand-written `new JsonWebTokenHandler()` in a test maps nothing by default, while `JwtBearer` maps by default.
- Does MapInboundClaims change what is inside the token or what the provider sends?No. The token and its signature are untouched; mapping happens after validation, when the handler builds the `ClaimsIdentity`. Only the claim types on `HttpContext.User` change, which is why the same token shows `sub` in a decoder and `nameidentifier` in the API.
- A handler event casts context.SecurityToken to JwtSecurityToken and gets null in ASP.NET Core 8 or later. Why?Since 8 the default token handler produces a `JsonWebToken`. Cast to `JsonWebToken` instead, or set `UseSecurityTokenValidators = true` to return to the obsolete `SecurityTokenValidators` path that still produces `JwtSecurityToken`.
- MapInboundClaims defaults to false, so claims keep their JWT names.
- Clear JwtSecurityTokenHandler.DefaultInboundClaimTypeMap to stop JwtBearer renaming claims in ASP.NET Core 10.
- With MapInboundClaims = false, role checks keep working with no other change.
- The name claim is mapped to ClaimTypes.Name, so User.Identity.Name is always filled.
- MapInboundClaims rewrites the claims inside the token before the signature check.
Assumes ASP.NET Core 10; since ASP.NET Core 8 JwtBearer validates with JsonWebTokenHandler, so its own DefaultInboundClaimTypeMap applies and clearing JwtSecurityTokenHandler's static map has no effect.