Course contentsShow
← C#
Lesson 1208 of 1,90811. Identity, Security, and ClaimsFree lesson

Claims Transformation for Authorization

Normalize incoming identity claims to fit application-specific authorization policies.

In this lesson, you will learn how to normalize incoming identity claims into a format that your authorization policies can easily understand and enforce.

The Bridge Between External Identity and Internal Policy

When you integrate third-party identity providers (like Google, Azure AD, or Auth0), you often have no control over the incoming claims. One provider might send a role as a comma-separated string roles: "admin,editor", while another sends multiple individual role claims. If your internal authorization policies expect a consistent format, your application will break or require messy, duplicated logic inside every controller.

Claims Transformation acts as a bridge. It intercepts the ClaimsPrincipal after authentication but before the authorization engine evaluates it. By implementing IClaimsTransformation, you can "normalize" these incoming identity claims into a standardized set of claims that your application expects.

Implementation Pattern

To implement this, create a class that implements IClaimsTransformation. Inside, you can inspect the incoming principal, add, remove, or modify claims, and return a new, "cleaned" principal:

public class ClaimsTransformation : IClaimsTransformation
{
    public Task<ClaimsPrincipal> TransformAsync(ClaimsPrincipal principal)
    {
        var clone = principal.Clone();
        var newIdentity = new ClaimsIdentity();

        // Normalize a custom external claim into a standard 'Role' claim
        if (principal.HasClaim(c => c.Type == "external_access_level"))
        {
            var level = principal.FindFirst("external_access_level")?.Value;
            if (level == "SUPER_USER")
            {
                newIdentity.AddClaim(new Claim(ClaimTypes.Role, "Admin"));
            }
        }

        clone.AddIdentity(newIdentity);
        return Task.FromResult(clone);
    }
}

By registering this in your Program.cs via builder.Services.AddTransient<IClaimsTransformation, ClaimsTransformation>();, the authorization middleware will always receive a consistent version of the user’s identity.

This approach keeps your authorization policies clean. Instead of writing logic that asks, "Does the user have the external_access_level claim OR the Role claim?", your policies can simply look for the Role claim, confident that the transformation layer has already handled the heavy lifting of normalization.

Key Takeaway: Claims transformation allows you to decouple your application's authorization logic from the idiosyncratic data formats of external identity providers by creating a consistent, internal identity standard.