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

📚 Interview question

How does role-based authorisation work in ASP.NET Core? Explain [Authorize(Roles = ...)] and RequireRole, how ASP.NET Core decides which claim is a role, how you combine roles with AND and OR, and where role-based authorisation stops scaling.

Role-based authorisation in ASP.NET Core: [Authorize(Roles)], RequireRole on policies and Minimal APIs, the role claim type and Entra app roles, AND vs OR semantics, and the role explosion problem.

Junior Theory Beginner aspnet-core authorization claims entra-id role-based-access-control security

🎯 Key points

  • A role is just a claim; IsInRole checks the identity's RoleClaimType, which each authentication handler can configure
  • [Authorize(Roles = "A,B")] is OR; stacking two [Authorize] attributes is AND
  • RequireRole in a named policy or RequireAuthorization(p => p.RequireRole(...)) on Minimal APIs
  • JWT/Entra: app roles arrive in the "roles" claim; JwtBearerOptions.MapInboundClaims still defaults to true in .NET 10, so set RoleClaimType when you turn it off
  • Role names as constants or policies, not string literals scattered through controllers
  • Keep roles (who you are) separate from permissions (what you may do); endpoints should check capabilities
  • Role explosion (Admin_NSW_ReadOnly...) is the signal to move to permission- or attribute-based checks
  • Roles answer 'what kind of user', never 'may this user touch this record'

⏱ 30-second answer

Role-based authorisation grants access by group membership. In ASP.NET Core a role is simply a claim on the ClaimsPrincipal; User.IsInRole("Admin") looks for a claim whose type equals the identity's RoleClaimType.

  • [Authorize(Roles = "Admin,Support")] means Admin OR Support; two stacked [Authorize] attributes mean AND.
  • In policies and Minimal APIs use RequireRole, ideally behind a named policy.
  • With Entra ID, app roles arrive in the roles claim, so set RoleClaimType = "roles" when inbound claim mapping is off.

The trade-off: roles are simple and auditable, but coarse. Once you need roles like Manager_NSW_ReadOnly you have role explosion, and policies, permissions or resource-based checks fit better.

🗣 Full answer (senior)

How I would answer this in an interview

"Role-based access control means you grant access by the group a user belongs to, like Admin, Support or Customer. In ASP.NET Core there is nothing special about a role: it is a claim on the ClaimsPrincipal. IsInRole and RequireRole just look for a claim whose type matches the identity's RoleClaimType. With cookie authentication and Identity that is ClaimTypes.Role; with Entra ID tokens the app roles come in a claim literally called roles, so if I turn off inbound claim mapping I set RoleClaimType = "roles" in the token validation parameters, otherwise IsInRole quietly returns false.

On an endpoint, [Authorize(Roles = "Admin,Support")] means either role is enough. If I need both, I stack two [Authorize] attributes, because every attribute must pass. For Minimal APIs I use RequireAuthorization with a named policy that calls RequireRole. I prefer named policies even for simple role checks: the endpoint says "CanRefund" and the policy decides which roles that means, so changing who can refund is one line instead of a search across forty controllers.

The mistake I see is using roles for everything. Roles answer 'what kind of user is this', not 'may this user edit this invoice'. Teams end up with roles like Manager_NSW_ReadOnly and dozens of combinations, which is role explosion. The senior line: roles are a good first layer for coarse areas of the app, but anything about specific records or fine-grained actions needs policies or resource-based checks."


The building blocks

Piece What it does
Role claim A claim whose type is ClaimsIdentity.RoleClaimType (default ClaimTypes.Role)
User.IsInRole("X") True if any identity on the principal has that role claim
[Authorize(Roles = "A,B")] Builds a RolesAuthorizationRequirement: A or B
Two [Authorize] attributes Both must pass: and
policy.RequireRole(...) The same requirement inside a named policy
RequireAuthorization("Policy") Applies a policy to a Minimal API endpoint or route group

Where roles come from

Source Claim type you see Watch out for
ASP.NET Core Identity ClaimTypes.Role Roles are read at sign-in; changes need re-sign-in or security stamp validation
Entra ID app roles roles Assigned on the enterprise app; set RoleClaimType if mapping is off
Entra ID groups groups (object ids) Overage above 200 groups in JWTs; prefer app roles
Your own database Added by IClaimsTransformation Cache it; it runs on every authenticated request

When roles fit and when they don't

Fits Doesn't fit
Back-office areas: admin, support, finance "Only the owner may edit this order"
A handful of stable roles Per-state, per-tenant or per-team variations
Coarse gating of whole controllers Fine-grained actions that product owners want to toggle

Production example

In an internal claims-processing app we had [11] roles and role strings in [140] attributes. Moving them behind [9] named policies cut the change to add a new "Senior Assessor" role from a [two-day] search-and-replace to a [one-line] policy change, and an authorisation test per policy caught [two] endpoints that had been left open.

🔍 What the interviewer is checking

Checks that the candidate knows a role is a claim, gets the AND/OR semantics right, and recognises when roles are the wrong tool.

Green flags

  • Explains RoleClaimType and the Entra roles claim
  • Knows comma means OR and stacked attributes mean AND
  • Hides role names behind named policies
  • Names role explosion and says roles don't protect individual records

Red flags

  • Thinks roles are stored somewhere separate from claims
  • Hard-codes role strings everywhere
  • Uses roles to answer ownership questions

📚 Learn in depth

1. A role is a claim

ClaimsPrincipal
 └─ ClaimsIdentity (AuthenticationType = "Bearer", RoleClaimType = "roles")
     ├─ sub   = 4f1c...
     ├─ name  = Priya
     ├─ roles = Support
     └─ roles = Refunds

User.IsInRole("Support")  ->  identity.HasClaim(identity.RoleClaimType, "Support")  ->  true

IsInRole checks every identity on the principal. The role claim type is a property of each identity, so the same token can produce different results depending on how the authentication handler built the identity.

2. How [Authorize(Roles)] becomes a requirement

At start-up, the authorisation policy provider combines all IAuthorizeData on the endpoint (controller and action attributes, or RequireAuthorization metadata) into one AuthorizationPolicy:

[Authorize(Roles = "Admin,Support")]   -> RolesAuthorizationRequirement { Admin, Support }   (any one)
[Authorize(Roles = "Auditor")]         -> RolesAuthorizationRequirement { Auditor }
Combined policy = DenyAnonymous + Req1 + Req2   (every requirement must succeed)

The built-in RolesAuthorizationRequirement is its own handler: it succeeds if User.IsInRole is true for any listed role.

3. Claim mapping and the role claim type

The JWT bearer handler historically mapped short claim names to long WS-Federation URIs (roles became http://schemas.microsoft.com/ws/2008/06/identity/claims/role), which is why role checks "just worked". With MapInboundClaims = false (common in new code so claim names match the token) you must tell the handler which claim is the role:

options.MapInboundClaims = false;
options.TokenValidationParameters.RoleClaimType = "roles";
options.TokenValidationParameters.NameClaimType = "name";

4. Role explosion

Roles multiply when you encode context into them: area x region x access level. Ten areas, eight states and three levels is 240 possible roles. Symptoms: role names with underscores, role assignment tickets that take days, and nobody able to say what a role allows. The fixes, in order of complexity:

  1. Named policies that hide which roles they accept.
  2. Claims for context (state = NSW) plus a policy that checks both.
  3. Permissions mapped from roles (see permission-based authorisation).
  4. Resource-based checks for anything about a specific record.

5. Roles and staleness

Roles in a cookie or JWT are a snapshot taken at sign-in. Removing someone from Admin doesn't take effect until the cookie is revalidated (Identity's security stamp check, every 30 minutes by default) or the access token expires. For high-risk roles, keep token lifetimes short or check the current role server-side.

Try it yourself

  1. Create a Minimal API with two policies and write WebApplicationFactory tests that prove OR and AND semantics.
  2. Decode an Entra ID access token on jwt.ms, find the roles claim, and make IsInRole work with MapInboundClaims = false.
  3. Grep a codebase for Roles = " and count distinct role strings; move them into constants and named policies.
  4. Remove a user from a role in Identity and measure how long their existing cookie still passes the check.

💻 Code

Role checks on controllers and Minimal APIs, with role names kept in one place and the role claim type set for Entra ID tokens.

// Program.cs (.NET 10)
using Microsoft.AspNetCore.Authorization;

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddAuthentication().AddJwtBearer(options =>
{
    options.Authority = builder.Configuration["Auth:Authority"];
    options.Audience = builder.Configuration["Auth:Audience"];
    options.MapInboundClaims = false;                       // keep claim names as in the token
    options.TokenValidationParameters.RoleClaimType = "roles"; // Entra ID app roles
    options.TokenValidationParameters.NameClaimType = "name";
});

// Endpoints name a capability; the policy decides which roles that means.
builder.Services.AddAuthorizationBuilder()
    .AddPolicy(Policies.CanRefund, p => p.RequireRole(Roles.Finance, Roles.Admin))   // OR
    .AddPolicy(Policies.CanExportAudit, p => p
        .RequireRole(Roles.Admin)
        .RequireRole(Roles.Auditor));                                                // AND

builder.Services.AddControllers();
var app = builder.Build();

app.UseAuthentication();
app.UseAuthorization();

var admin = app.MapGroup("/admin").RequireAuthorization(p => p.RequireRole(Roles.Admin));
admin.MapPost("/refunds/{id:int}", (int id) => Results.Accepted())
     .RequireAuthorization(Policies.CanRefund);

app.MapControllers();
app.Run();

public static class Roles
{
    public const string Admin = "Admin";
    public const string Finance = "Finance";
    public const string Auditor = "Auditor";
}

public static class Policies
{
    public const string CanRefund = nameof(CanRefund);
    public const string CanExportAudit = nameof(CanExportAudit);
}
// Controllers/ReportsController.cs
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;

namespace Claims.Api.Controllers;

[ApiController]
[Route("reports")]
[Authorize(Roles = Roles.Admin + "," + Roles.Finance)]   // Admin OR Finance for the whole controller
public sealed class ReportsController : ControllerBase
{
    [HttpGet("audit")]
    [Authorize(Policy = Policies.CanExportAudit)]          // adds a second requirement: AND
    public IActionResult Audit() => Ok();
}

⚠ Common mistakes

  • Mistake: Assuming [Authorize(Roles = "A,B")] requires both roles. Why it is wrong: the comma means any one of them. Instead: stack two [Authorize] attributes or call RequireRole twice in a policy for AND.
  • Mistake: Turning off MapInboundClaims and not setting RoleClaimType. Why it is wrong: the roles claim is present but IsInRole looks for a different claim type, so every role check returns 403. Instead: set TokenValidationParameters.RoleClaimType = "roles".
  • Mistake: Setting a custom RoleClaimType (for example "role") that doesn't match what the identity provider or your IClaimsTransformation actually emits. Why it is wrong: role claims exist under another type, so role checks fail with no error, only 403s. Instead: decode a real token on jwt.ms, confirm the claim name, and cover it with an integration test that signs in a user with a role.
  • Mistake: Role strings as literals in dozens of attributes. Why it is wrong: a typo silently denies (or a rename silently breaks) access, and nobody can see who can do what. Instead: constants plus named policies.
  • Mistake: Encoding context into role names (Manager_NSW). Why it is wrong: the number of roles multiplies and nobody can audit them. Instead: a role plus a claim, or permissions.
  • Mistake: Using roles to protect specific records. Why it is wrong: being a Customer doesn't mean you own order 123. Instead: resource-based authorisation.
  • Mistake: Using Entra ID groups instead of app roles for app permissions. Why it is wrong: groups are object ids, and JWTs drop the claim once a user is in more than 200 groups. Instead: app roles assigned on the enterprise application.

🏛 Senior insight: trade-offs

Roles are the cheapest authorisation model to explain to auditors, which is why they survive in every enterprise. I keep them, but treat them as an input to policies rather than the thing endpoints check directly. The endpoint names a capability, the policy maps capabilities to roles, and resource checks handle ownership.

Option When it fits Cost When not to
Roles on attributes Small app, 3-5 stable roles Lowest Many roles, frequent changes
Named policies over roles Most line-of-business apps One extra indirection Never really wrong
Permissions mapped from roles Product wants configurable access A permission store and caching Small, stable apps
Resource-based checks Ownership, tenant, record state Code per resource type Coarse area gating

Measure it: count distinct role strings, policies and the endpoints with no authorisation metadata. An integration test that enumerates EndpointDataSource and fails on unprotected endpoints is cheap and catches the most common gap.

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions MapInboundClaims or role claims from Entra ID Why: Checks they understand where role claims come from and how mapping changes them
    How to 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.

  2. When: Candidate mentions UseAuthorization or 401 vs 403 Why: Checks they can separate authentication from authorisation and the middleware order
    How to answer

    Authentication answers who are you? and authorisation answers what are you allowed to do? In ASP.NET Core, authentication is built from schemes: a name plus an authentication handler (cookies, JwtBearer, OpenIdConnect, or your own). The handler reads a credential from the request, validates it and produces a ClaimsPrincipal, which the authentication middleware puts on HttpContext.User. The authorisation middleware then checks the endpoint's [Authorize] metadata against that principal: no identity means a challenge (401 or a login redirect), an identity without permission means forbid (403).

    Order matters: UseAuthentication must run before UseAuthorization, and both after routing and CORS, or the user is anonymous when the decision is made. The trade-off is flexibility versus clarity: several schemes are powerful, but every extra scheme is another way to be authenticated by accident.

More in Authorization

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me