In ASP.NET Core, when does IClaimsTransformation.TransformAsync run, and what goes wrong when it is used to add claims from a database?
answer
- runs inside AuthenticateAsync
- may run more than once
- never written back to the cookie
- default NoopClaimsTransformation singleton
- OnValidatePrincipal with ReplacePrincipal
basics
~20 sIClaimsTransformation.TransformAsync runs after every successful AuthenticateAsync, on every authenticated request and possibly several times per request. Its claims are never saved to the cookie, so it must be idempotent and cheap, or each request pays a database lookup.
solid answer
~40 s`IAuthenticationService.AuthenticateAsync` passes every successful principal through the registered `IClaimsTransformation` before returning it; the default registration is a `NoopClaimsTransformation` singleton, which you replace with `AddTransient` or `AddScoped` (scoped if it needs a `DbContext`). It runs on each authenticated request, for whichever scheme succeeded, and the docs warn it may run more than once, so it must check whether its claims already exist and should add them to a clone or a new `ClaimsIdentity` rather than duplicating them. Nothing it adds is persisted: the cookie still holds the original ticket, so a database lookup in it runs per request unless you cache. When the extra claims are stable, add them before `SignInAsync` or in `OnSigningIn`; when they must be refreshed, `OnValidatePrincipal` with `ReplacePrincipal` and `ShouldRenew` rewrites the cookie.
code
csharp · 23 linespublic sealed class PupilClaims(SchoolDb db, IMemoryCache cache) : IClaimsTransformation
{
public async Task<ClaimsPrincipal> TransformAsync(ClaimsPrincipal principal)
{
if (principal.Identity?.AuthenticationType != CookieAuthenticationDefaults.AuthenticationScheme
|| principal.HasClaim(c => c.Type == "pupil"))
return principal;
var parentId = principal.FindFirstValue(ClaimTypes.NameIdentifier)!;
var pupils = await cache.GetOrCreateAsync($"pupils:{parentId}", entry =>
{
entry.AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(5);
return db.PupilIdsFor(parentId);
});
var clone = principal.Clone();
((ClaimsIdentity)clone.Identity!).AddClaims(pupils!.Select(id => new Claim("pupil", id)));
return clone;
}
}
// Program.cs
builder.Services.AddScoped<IClaimsTransformation, PupilClaims>();go deeper
Remember that IClaimsTransformation can add claims to the signed-in user after authentication, and that it runs again on each request.
Explain where it is called, why it must be idempotent, why its claims are not persisted, and which lifetime it needs when it uses a DbContext.
Choose between per-request transformation with caching, claims added at sign-in, and OnValidatePrincipal refresh, judging staleness against per-request cost.
Decide which facts belong in the identity at all versus being looked up by authorization at decision time, considering revocation latency and cookie size.
## Where the hook sits `IClaimsTransformation` has one method, `Task<ClaimsPrincipal> TransformAsync(ClaimsPrincipal principal)`. It is called by `AuthenticationService.AuthenticateAsync`, the scoped service behind `HttpContext.AuthenticateAsync`, **after** a scheme's handler succeeds and **before** the result is returned. So it runs: - when the authentication middleware authenticates the default scheme on each request; - when authorization re-authenticates for a policy or endpoint that names other schemes; - when your own code calls `HttpContext.AuthenticateAsync(...)`. The interface's own documentation says it runs on each `AuthenticateAsync` call and advises returning a new principal if the transformation is not idempotent. The conceptual docs repeat that it "might be called multiple times" and to add a claim only if it is not already there. ## Registration and lifetime `AddAuthentication` registers `NoopClaimsTransformation` with `TryAddSingleton`, returning the principal unchanged. Register your own afterwards; `TryAdd` will not override it, but a plain `AddTransient<IClaimsTransformation, PupilClaims>()` or `AddScoped<...>()` does, because the last registration wins on resolution. A transformation that injects a `DbContext` must be **transient or scoped**; making it a singleton captures the scoped context. ## The three ways it goes wrong 1. **Duplicated claims.** A transformation that blindly appends `new Claim("pupil", id)` to `principal.Identity` adds it again on every call within a request, so `FindAll("pupil")` returns duplicates. Check first, or build a separate `ClaimsIdentity` and add it with `AddIdentity` only when absent. 2. **A database query per request.** The transformed claims are not written into the cookie. The ticket in the cookie is still the one created at sign-in, so the lookup repeats on every request. For a parents' portal reading which pupils a parent may see, that is one query per page and per API call. Cache by user id with a short expiry, or move the claims elsewhere. 3. **Assuming one scheme.** It runs for whichever scheme succeeded. A partner principal from an API-key scheme also passes through, so a transformation written for parents must check `principal.Identity?.AuthenticationType` or a claim before acting. ## Alternatives and when each fits | Need | Mechanism | Persisted in the cookie? | |---|---|---| | Claims known at sign-in and stable | add them before `SignInAsync`, or in `CookieAuthenticationEvents.OnSigningIn` | yes | | Claims that change and must be refreshed | `OnValidatePrincipal`: build a new principal, `ReplacePrincipal`, set `ShouldRenew = true` | yes, after renewal | | Revoke a user whose account changed | `OnValidatePrincipal`: `RejectPrincipal()` and `SignOutAsync` | the cookie is removed | | Per-request enrichment for any scheme | `IClaimsTransformation` | no | Two notes on the cookie events: - `OnValidatePrincipal` runs on every cookie authentication too, so a check there should be cheap or throttled, for example only re-querying when a timestamp claim is older than a few minutes. - Putting many claims into the cookie grows every request; the chunking cookie manager will split it, but it is still bytes on the wire. ## Choosing for the scenario For the portal: put the parent id and name in the cookie at sign-in. Load the pupil links in an `IClaimsTransformation` backed by a short cache **or**, if pupils rarely change, add them at sign-in and refresh them from `OnValidatePrincipal` when a school-side change stamp moves. Whichever is chosen, resource checks such as "may this parent see this pupil's report?" belong to authorization, which reads these claims; the transformation only supplies them. ## Quick test of understanding - Does it run for a request with no cookie? No: it runs only after a scheme **succeeds**. - Does it run for the partner key scheme? Yes, for any successful scheme. - Will `User` in the next request contain the added claims without running it again? No: nothing is persisted.
- Could the transformation be registered as a singleton if it injects SchoolDb, a DbContext?No. A singleton would capture one scoped `DbContext` for the life of the app, sharing it across concurrent requests, which `DbContext` does not support. Register the transformation as scoped or transient, or inject `IDbContextFactory<T>` into a singleton and create a context per call.
- A pupil is unlinked from a parent. With the transformation above, how long until the parent loses access, and how would you make it immediate?Up to the five-minute cache expiry, because claims are rebuilt per request from the cache. To make it immediate, evict the cache entry when the link changes; if the pupil claims lived in the cookie instead, `OnValidatePrincipal` would need a change stamp to replace or reject the principal.
- Claims added in IClaimsTransformation are saved into the authentication cookie.
- TransformAsync runs exactly once per request, so it never needs to check for existing claims.
- It only runs for the cookie scheme, never for other schemes.
- Registering it as a singleton is fine even when it injects a DbContext.
- Replacing the default needs RemoveAll before AddScoped, because TryAddSingleton blocks later registrations.