With ASP.NET Core's AddOpenIdConnect, why can a claim the identity provider issues be missing from HttpContext.User, and which options bring it back?
answer
- built from the ID token first
- Scope defaults to openid and profile
- GetClaimsFromUserInfoEndpoint defaults to false
- ClaimActions: MapJsonKey, DeleteClaim, Remove
- OnTokenValidated for your own claims
basics
~20 sThe OpenID Connect handler builds User from the validated ID token, deletes protocol claims via ClaimActions and reads userinfo only when GetClaimsFromUserInfoEndpoint is true. Even then a userinfo field becomes a claim only if a ClaimAction maps its JSON key.
solid answer
~40 sWalk the pipeline. First, the claim must be **requested**: `Scope` holds only `openid` and `profile` by default, so `email` or a custom scope must be added. Second, many providers put profile data only at **userinfo**: `GetClaimsFromUserInfoEndpoint` is `false` by default, and it needs an access token, so the code flow. Third, userinfo JSON reaches `User` only through `ClaimActions`: the defaults map `sub`, `name`, `given_name`, `family_name`, `profile` and `email`, so a `department` field needs `ClaimActions.MapJsonKey("department", "department")` or `MapUniqueJsonKey`. Fourth, the default actions **delete** protocol claims such as `nonce`, `aud`, `iss`, `exp` and `at_hash`; `ClaimActions.Remove("iss")` keeps one. Finally, `MapInboundClaims` (default `true`) renames types like `email` to the long `ClaimTypes` URIs. Claims from your own database belong in `OnTokenValidated`, which runs once per sign-in.
code
csharp · 21 lines.AddOpenIdConnect(options =>
{
// Authority, ClientId, ClientSecret as before
options.ResponseType = OpenIdConnectResponseType.Code;
options.Scope.Add("email");
options.GetClaimsFromUserInfoEndpoint = true;
options.ClaimActions.MapUniqueJsonKey("department", "department");
options.ClaimActions.Remove("acr"); // keep acr for step-up policies
options.MapInboundClaims = false;
options.TokenValidationParameters.NameClaimType = "name";
options.TokenValidationParameters.RoleClaimType = "roles";
options.Events.OnTokenValidated = async context =>
{
var staff = context.HttpContext.RequestServices.GetRequiredService<IStaffDirectory>();
var costCentre = await staff.GetCostCentreAsync(context.Principal!.FindFirst("sub")!.Value);
((ClaimsIdentity)context.Principal.Identity!).AddClaim(new Claim("cost_centre", costCentre));
};
});go deeper
Recall that claims come from the ID token and, optionally, the userinfo endpoint, and that a scope must be requested for the provider to send its claims.
Explain the stages that build the principal, the default Scope, GetClaimsFromUserInfoEndpoint and ClaimActions lists, and how MapInboundClaims renames claim types.
Diagnose a missing claim methodically, keep the cookie small, and choose between sign-in-time claims in OnTokenValidated and per-request lookups for data that changes.
Agree with the identity team which claims the provider issues and which the application derives, so apps do not each invent their own mapping.
## How the principal is built When the identity provider (IdP) returns to `/signin-oidc`, `OpenIdConnectHandler` builds the user in stages: 1. It validates the **ID token** and turns its claims into a `ClaimsIdentity`. The token handler applies `MapInboundClaims` (default `true`), which renames short claim types such as `email` or `sub` to the long `ClaimTypes` URIs. 2. It raises `OnTokenValidated`, where your code may add, remove or replace claims. 3. If `GetClaimsFromUserInfoEndpoint` is `true` **and** an access token was issued, it calls the provider's userinfo endpoint with that token, raises `OnUserInformationReceived`, and runs every `ClaimAction` against the returned JSON. 4. If userinfo is not used, it still runs the `ClaimActions` against an empty JSON object, so the delete actions always apply. 5. The finished principal is signed into the cookie scheme. A claim can drop out at any of these stages. ## Reason 1: it was never requested `OpenIdConnectOptions.Scope` starts with `openid` and `profile`. An `email` claim usually needs the `email` scope, and organisation-specific data often needs a custom scope. Add it with `options.Scope.Add("email")`. ## Reason 2: it lives only at userinfo Many providers keep the ID token small and serve profile data from the userinfo endpoint. `GetClaimsFromUserInfoEndpoint` defaults to `false`. Turning it on helps only in a flow that yields an access token: with the default `ResponseType = "id_token"` the handler logs that no access token is available and skips the call. Use `ResponseType = OpenIdConnectResponseType.Code`. ## Reason 3: no ClaimAction maps it Userinfo JSON does not flow into `User` wholesale. Only JSON keys named by a `ClaimAction` become claims. The constructor registers: - `MapUniqueJsonKey` for `sub`, `name`, `given_name`, `family_name`, `profile` and `email`; - `DeleteClaim` for `nonce`, `aud`, `azp`, `acr`, `iss`, `iat`, `nbf`, `exp`, `at_hash`, `c_hash`, `ipaddr`, `platf` and `ver`. The `ClaimActions` methods you use: | Method | Effect | |---|---| | `MapJsonKey(claimType, jsonKey)` | adds a claim for the key; arrays become several claims | | `MapUniqueJsonKey(claimType, jsonKey)` | the same, but skips the claim if one with that type and value already exists | | `MapJsonSubKey(claimType, jsonKey, subKey)` | reads a nested property | | `MapAll()` / `MapAllExcept(...)` | maps every key, or every key but some | | `DeleteClaim(type)` / `DeleteClaims(...)` | removes claims of that type from the identity | | `Remove(type)` | removes the actions registered for that type, for example to keep `acr` | ## Reason 4: it was deleted on purpose The default delete list strips protocol claims that mean nothing to the application and would bloat the cookie. If a policy really needs one, say `acr` for step-up checks, call `options.ClaimActions.Remove("acr")` so the delete action is no longer registered. A delete action matches the claim type exactly: with `MapInboundClaims = true`, `acr` is first renamed to a long Microsoft claim URI and so survives anyway, while unmapped types such as `nonce`, `aud`, `iss` and `exp` are always removed. ## Reason 5: it is there under another name With `MapInboundClaims = true`, an `email` claim from the ID token is stored under the type `ClaimTypes.Email`, so `User.FindFirst("email")` misses it. Many apps set `MapInboundClaims = false` and then also set `TokenValidationParameters.NameClaimType = "name"` and `RoleClaimType` to the provider's role claim, otherwise `User.Identity.Name` is `null` and `IsInRole` finds nothing. ## Adding the application's own claims Claims that come from the intranet's own database, such as a cost centre, belong in `OpenIdConnectEvents.OnTokenValidated` (or `OnTicketReceived`). These run **once per sign-in**, and the result is stored in the cookie. Two cautions: - every claim added here travels in the cookie, so keep the set small; - the values are frozen until the next sign-in, so data that changes often is better looked up per request. ## Diagnosing 1. Decode the ID token and the userinfo response and check whether the provider sent the value at all. 2. Check `Scope`, `ResponseType` and `GetClaimsFromUserInfoEndpoint`. 3. Check `ClaimActions` for a mapping or a delete. 4. Dump `User.Claims` and look for the value under a renamed type.
- What does calling ClaimActions.MapAll() cost you?Every userinfo key becomes a claim, so the principal and therefore the sign-in cookie grow, and protocol or duplicate values come along. Once the cookie passes about 4,050 characters the default `ChunkingCookieManager` splits it into several cookies sent on every request. Map the keys you need with `MapJsonKey` or `MapUniqueJsonKey` instead.
- GetClaimsFromUserInfoEndpoint is true, yet no userinfo request is ever sent. What would you check?Whether an access token was issued at all: with the default `id_token` response type there is none and the handler skips the call. Also check that the discovery document lists a userinfo endpoint; without one the handler logs it and moves on.
- The handler copies every userinfo field into User automatically.
- GetClaimsFromUserInfoEndpoint is enabled by default.
- The ID token's aud and exp claims stay on User for policies to use.
- OnTokenValidated runs on every request, so it is too slow for a database lookup.
- Setting MapInboundClaims to false alone makes User.Identity.Name return the name claim.