📁 Sangam Dhakal - Portfolio v2.0 - Netscape Navigator 4.0
_
□
×

📚 Interview question

How do claims and roles work in ASP.NET Core? Explain what a claim is, how inbound claim mapping (MapInboundClaims) changes claim names, how IClaimsTransformation adds claims, and where an application's permissions should come from: the token, the database or both.

Claims and roles in ASP.NET Core: ClaimsPrincipal and ClaimsIdentity, NameClaimType and RoleClaimType, inbound claim mapping, IClaimsTransformation, and sourcing permissions from tokens vs the application.

Intermediate Theory Intermediate aspnet-core authorization claims entra-id jwt security

🎯 Key points

  • A claim is a type/value statement from an issuer; a role is just a claim type
  • ClaimsIdentity.NameClaimType and RoleClaimType drive Identity.Name and IsInRole
  • MapInboundClaims (default true) renames short JWT claims (sub, role, email...) to WS-Fed URIs; false keeps the issued names
  • IClaimsTransformation runs on every AuthenticateAsync, possibly several times per request: idempotent, cloned principal, cached lookup
  • Roles gate broad areas (Manager can open Approvals); permissions gate actions (invoice.approve), mapped role -> permission in the app
  • Only trust claims from your IdP or your own store, never self-asserted ones
  • Entra ID: oid as the key, scp for delegated scopes, roles for app roles, groups overage above 200
  • Big tokens cost on every request: chunked cookies, 431 errors, stale permissions

⏱ 30-second answer

A claim is a type/value statement about the user made by an issuer, such as sub=42 or roles=Admin. A ClaimsPrincipal holds one or more ClaimsIdentity objects; each identity's NameClaimType and RoleClaimType decide what User.Identity.Name and User.IsInRole read, so a role is just a claim.

The JWT and OIDC handlers map inbound claims by default (sub becomes ClaimTypes.NameIdentifier); MapInboundClaims = false keeps the issuer's names. IClaimsTransformation can add application claims after authentication, but it runs on every authenticate call, so it must be idempotent and cached.

Permissions: take identity and coarse roles from the identity provider, and fine-grained, app-specific permissions from your own store. The trade-off is token size and staleness versus a lookup per request.

🗣 Full answer (senior)

How I would answer this in an interview

"A claim is a statement about the subject, issued by someone you trust: a type, a value and an issuer. The identity provider puts claims in the token, the authentication handler turns them into a ClaimsIdentity, and the ClaimsPrincipal on HttpContext.User is the collection of identities. Roles aren't a separate concept: IsInRole simply looks for claims of the identity's RoleClaimType, and [Authorize(Roles = \"Admin\")] uses the same thing.

The surprise for most people is claim mapping. By default the JWT bearer and OpenID Connect handlers rename short JWT claim names to the long WS-Federation URIs, so sub shows up as http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier. If you set MapInboundClaims = false you get sub, roles and scp as issued, which is easier to reason about, but then you must set NameClaimType and RoleClaimType or Identity.Name is null and role checks stop matching. When the token doesn't carry what the app needs, IClaimsTransformation lets you add claims, for example the user's tenant or their permissions from the database. It runs every time the principal is authenticated, which can be more than once per request, so it has to be idempotent and should hit a cache, not the database every time.

The mistake I see is pushing every permission into the token or cookie, until it's 8 KB and stale for an hour. The senior line: the identity provider knows who the user is; the application knows what they may do in it."


The pieces

Concept API Note
Claim Claim(type, value, valueType, issuer) Immutable statement
Identity ClaimsIdentity(claims, authenticationType, nameType, roleType) IsAuthenticated is true when authenticationType is set
Principal ClaimsPrincipal HttpContext.User; can hold several identities
Name Identity.Name Reads NameClaimType
Roles IsInRole, RequireRole Read RoleClaimType

Where permissions come from

Source Good for Weakness
IdP token (roles, groups, scopes) Coarse roles, app roles, delegated scopes Stale until token refresh; size limits; IdP admins own it
App database via claims transformation Fine-grained, per-tenant, per-resource permissions Lookup cost; needs caching and invalidation
Resource-based checks at runtime Ownership ('only the author may edit') Can't be expressed as claims at all

Microsoft Entra ID claims worth knowing

Claim Meaning
oid Stable user object id in the tenant (use this, not email, as the key)
tid Tenant id
scp Space-separated delegated scopes
roles App roles (users or applications)
groups Group ids; above 200 groups in a JWT you get an overage claim instead

Production example

At [company], a [B2B] app put all [~150] permissions into the cookie as claims, hitting 3 chunked cookies and [~9 KB] per request. Moving permissions to a claims transformation backed by a 5-minute HybridCache entry cut the cookie to [~1 KB] and made permission changes take effect in minutes instead of at next sign-in.

🔍 What the interviewer is checking

Checks that the candidate understands claims as the data model of identity in .NET and makes sensible choices about where permission data comes from.

Green flags

  • Explains NameClaimType / RoleClaimType and claim mapping
  • Knows IClaimsTransformation runs repeatedly and must be idempotent
  • Separates identity facts (IdP) from app permissions (app)
  • Mentions token size, staleness and Entra specifics like oid, scp, roles

Red flags

  • Thinks roles are separate from claims
  • Puts every permission in the JWT
  • Uses email as the primary user key

📚 Learn in depth

1. From token to principal

JWT payload {sub, name, roles:["Admin"], scp:"Orders.Read"}
   -> JsonWebTokenHandler validates
   -> claim mapping (if MapInboundClaims) : sub -> ...nameidentifier, roles -> ...role
   -> ClaimsIdentity(authenticationType: "AuthenticationTypes.Federation",
                     nameType: options.NameClaimType, roleType: options.RoleClaimType)
   -> AuthenticateResult -> HttpContext.User
   -> IClaimsTransformation.TransformAsync(principal)  (if registered)

The mapping table lives in JsonWebTokenHandler.DefaultInboundClaimTypeMap (and the older JwtSecurityTokenHandler.DefaultInboundClaimTypeMap). Setting the option per scheme is cleaner than clearing the global map.

2. Claims transformation rules

IClaimsTransformation is called by AuthenticationService.AuthenticateAsync. Anything that calls authenticate, including the middleware, authorisation and some handlers, triggers it, so:

  • Check whether your claims are already present before adding them (idempotent).
  • Return a new principal or clone the identity instead of mutating a shared one.
  • Cache per user (with HybridCache or IMemoryCache) and accept a short staleness window.
  • Register it as scoped if it needs a DbContext.

3. Roles vs permissions

Roles describe people (Clerk, Manager); permissions describe actions (invoice.approve). Mapping roles to permissions inside the app means a new role doesn't require code changes, and policies check permissions. That is the subject of permission-based authorisation, but the claims layer is where the data arrives.

4. Size and staleness

Cookies over ~4 KB are chunked; headers over Kestrel's 32 KB request header limit fail with 431. Tokens carry claims until they expire, so a revoked role lingers for the access token lifetime. Group claims in Entra ID overflow at 200 groups in a JWT, replaced by a _claim_names / hasgroups indicator that tells you to query Microsoft Graph.

Try it yourself

  1. Log User.Claims for a JWT with and without MapInboundClaims and compare the types.
  2. Set MapInboundClaims = false without changing RoleClaimType and watch a [Authorize(Roles = ...)] endpoint return 403.
  3. Write an IClaimsTransformation that logs each call; count how many times it runs per request.
  4. Add HybridCache to the transformation and measure database calls under a k6 load test.
  5. Assign 210 groups to a test user in a dev tenant and inspect the token for the overage claim.

💻 Code

Keeping issued claim names, then adding application permissions with a cached, idempotent claims transformation.

// Program.cs (.NET 10)
using System.Security.Claims;
using Microsoft.AspNetCore.Authentication;
using Microsoft.Extensions.Caching.Hybrid;

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddAuthentication().AddJwtBearer(o =>
{
    o.Authority = builder.Configuration["Auth:Authority"];
    o.Audience = builder.Configuration["Auth:Audience"];
    o.MapInboundClaims = false;                     // keep 'sub', 'roles', 'scp'
    o.TokenValidationParameters.NameClaimType = "name";
    o.TokenValidationParameters.RoleClaimType = "roles";
});
builder.Services.AddHybridCache();
builder.Services.AddScoped<IPermissionStore, SqlPermissionStore>();
builder.Services.AddScoped<IClaimsTransformation, PermissionClaimsTransformation>();
builder.Services.AddAuthorization();

var app = builder.Build();
app.UseAuthentication();
app.UseAuthorization();
app.MapGet("/invoices/approve", () => Results.Ok())
   .RequireAuthorization(p => p.RequireClaim("perm", "invoice.approve"));
app.Run();

public interface IPermissionStore
{
    Task<string[]> GetPermissionsAsync(string userId, CancellationToken ct);
}

public sealed class SqlPermissionStore : IPermissionStore
{
    // Real code would query role -> permission tables with EF Core.
    public Task<string[]> GetPermissionsAsync(string userId, CancellationToken ct) =>
        Task.FromResult<string[]>(["invoice.read", "invoice.approve"]);
}

public sealed class PermissionClaimsTransformation(IPermissionStore store, HybridCache cache) : IClaimsTransformation
{
    private const string AppIdentity = "app-permissions";

    public async Task<ClaimsPrincipal> TransformAsync(ClaimsPrincipal principal)
    {
        // Idempotent: this can run several times per request.
        if (principal.Identities.Any(i => i.AuthenticationType == AppIdentity))
            return principal;

        var userId = principal.FindFirstValue("sub");
        if (userId is null) return principal;

        var permissions = await cache.GetOrCreateAsync(
            $"perms:{userId}",
            async ct => await store.GetPermissionsAsync(userId, ct),
            new HybridCacheEntryOptions { Expiration = TimeSpan.FromMinutes(5) });

        var clone = principal.Clone();   // don't mutate the original
        clone.AddIdentity(new ClaimsIdentity(permissions.Select(p => new Claim("perm", p)), AppIdentity));
        return clone;
    }
}

⚠ Common mistakes

  • Mistake: Setting MapInboundClaims = false without setting NameClaimType and RoleClaimType. Why it is wrong: Identity.Name becomes null and role checks quietly fail. Instead: configure both whenever you change mapping.
  • Mistake: Using email or name as the user key. Why it is wrong: they change and aren't unique across tenants or IdPs. Instead: sub, or oid + tid in Entra ID.
  • Mistake: Querying the database in IClaimsTransformation on every call. Why it is wrong: it runs several times per request and multiplies database load. Instead: make it idempotent and cache per user.
  • Mistake: Mutating the incoming principal in the transformation. Why it is wrong: repeated calls add duplicate claims. Instead: clone and add a separate identity, or check before adding.
  • Mistake: Putting hundreds of permissions or group ids in tokens and cookies. Why it is wrong: chunked cookies, 431 errors, overage claims and stale permissions. Instead: coarse roles in the token; permissions looked up and cached.
  • Mistake: Trusting claims a client can influence, such as a self-asserted role from a registration form. Why it is wrong: privilege escalation. Instead: only trust claims from your IdP or your own store.
  • Mistake: Checking delegated scopes and app roles as if they were the same. Why it is wrong: a daemon token has roles but no scp; a user token may have both meanings. Instead: separate policies for delegated (scp) and application (roles) access.

🏛 Senior insight: trade-offs

Claims are inputs, not decisions. A senior design keeps the token small and stable (who the user is, which tenant, coarse roles), adds app-specific permissions in one cached place, and makes policies the only place that interprets them. The staleness window is a business decision: say it out loud ('a revoked permission lasts up to 5 minutes') and pick cache and token lifetimes to match.

Option When it fits Cost When not to
Roles in the IdP token A few stable roles, admins manage them in Entra Stale until token refresh Per-tenant or per-resource permissions
Claims transformation + cache Fine-grained app permissions Cache, invalidation, one lookup per user per window When permissions are needed in other services too (consider a permission service)
Permissions in a custom token from your own STS Many services need the same permissions Token size, issuing infrastructure Small apps

Measure cookie and header sizes, transformation call counts per request, and cache hit rate.

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions claims coming from the JWT Why: Checks how the token is validated before claims are trusted
    How to answer

    A JWT is three base64url parts, header.payload.signature. The header says which algorithm and key (alg, kid) signed it; the payload holds claims (iss, aud, sub, exp, scopes); the signature proves nobody changed them. It is signed, not encrypted, so anyone holding it can read it: no personal or secret data.

    • RS256/ES256: the identity provider signs with a private key and APIs verify with the public key from its JWKS endpoint. HS256 uses one shared secret, so every verifier could also forge tokens.
    • In ASP.NET Core, AddJwtBearer with Authority and Audience validates issuer, audience, lifetime and signature (with a 5-minute ClockSkew).

    The trade-off: validation is local and fast, but a stolen token is valid until exp, so keep access tokens short-lived.

  2. When: Candidate suggests using group claims for authorisation Why: Checks awareness of the groups overage limit and app roles
    How to answer

    Entra ID limits how many group ids it puts in a token: above 200 groups in a JWT (150 for SAML, 6 for implicit flow) it omits the groups claim and adds an overage indicator (_claim_names / _claim_sources pointing at Microsoft Graph, or hasgroups in some flows), so the app must call Graph (/me/getMemberObjects or /users/{id}/transitiveMemberOf) to get memberships, which needs a Graph permission, adds latency and should be cached. Better designs avoid raw groups: define app roles and assign them to groups, so the token carries a short roles list; or set the group claim to 'groups assigned to the application' only; or keep fine-grained permissions in the app and cache them. Code must handle the overage case explicitly, or users silently lose access.

↩ Usually asked after

More in Authentication

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me