How do claims transformations (IClaimsTransformation) let you augment a user's claims after initial authentication but before authorization checks run?
Short answer
IClaimsTransformation.TransformAsync is called automatically after authentication succeeds, letting you add additional claims not present in the original token/cookie -- such as fetching a user's current roles or permissions from a database that may change more frequently than…
Advertisement
AModel answer
IClaimsTransformation.TransformAsync is called automatically after authentication succeeds, letting you add additional claims not present in the original token/cookie -- such as fetching a user's current roles or permissions from a database that may change more frequently than the token itself, avoiding the need to reissue a new token every time such data changes.
public class RolesClaimsTransformer : IClaimsTransformation {
public async Task<ClaimsPrincipal> TransformAsync(ClaimsPrincipal principal) {
var identity = (ClaimsIdentity)principal.Identity;
if (!identity.HasClaim(c => c.Type == "enriched")) {
var roles = await _roleService.GetRolesAsync(principal.FindFirst("sub").Value);
foreach (var role in roles) identity.AddClaim(new Claim(ClaimTypes.Role, role));
identity.AddClaim(new Claim("enriched", "true"));
}
return principal;
}
}Real-world example
An application whose user roles can change mid-session (an admin revokes a permission) uses claims transformation to fetch current roles from the database on every request, rather than relying on potentially stale roles baked into a long-lived JWT.
Likely follow-ups
- What's the performance cost of a database call on every request via claims transformation, and how would you cache it?
- How does this differ from simply putting more claims directly in the original token?
Related topics