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

📚 Interview question

What are claims-based and policy-based authorisation in ASP.NET Core? Explain policies, requirements and handlers, how RequireAuthorization works on Minimal API endpoints and route groups, and the difference between the default policy and the fallback policy.

Policy-based authorisation in ASP.NET Core: AuthorizationPolicy, requirements and handlers, RequireClaim and RequireAssertion, AND/OR evaluation, RequireAuthorization on Minimal APIs and groups, AllowAnonymous, and DefaultPolicy vs FallbackPolicy.

Intermediate Theory Intermediate aspnet-core authorization claims minimal-apis policy-based-authorization security

🎯 Key points

  • A policy is a named list of requirements; every requirement must succeed (AND)
  • A requirement is data (IAuthorizationRequirement); handlers decide; any handler succeeding satisfies it (OR) unless one calls Fail
  • RequireClaim, RequireRole, RequireAuthenticatedUser, RequireAssertion are built-in requirement shortcuts
  • AddAuthorizationBuilder().AddPolicy(...) (.NET 7+); apply with [Authorize(Policy)] on controllers, RequireAuthorization on endpoints, MapGroup or MapControllers()
  • DefaultPolicy: used by [Authorize] with no policy; FallbackPolicy: used when an endpoint has no authorisation metadata at all
  • FallbackPolicy = RequireAuthenticatedUser makes the app secure by default; [AllowAnonymous] / AllowAnonymous() opt out
  • Custom requirements and handlers (or a custom IAuthorizationPolicyProvider) for rules that need data or services
  • Policies are evaluated by AuthorizationMiddleware after routing using endpoint metadata

⏱ 30-second answer

Policy-based authorisation separates what an endpoint needs from how it is checked. A policy is a named set of requirements; each requirement is plain data (IAuthorizationRequirement) and one or more handlers decide whether it is met. All requirements must pass; for a single requirement, any handler succeeding is enough unless one explicitly fails. Claims-based checks (RequireClaim("scope", "orders.read")) are just built-in requirements.

  • Apply with [Authorize(Policy = "...")] or RequireAuthorization("...") on Minimal API endpoints and MapGroup.
  • DefaultPolicy is what plain [Authorize] uses; FallbackPolicy applies to endpoints with no authorisation metadata.

The trade-off: a fallback policy makes the app secure by default, at the cost of explicitly marking public endpoints with AllowAnonymous.

🗣 Full answer (senior)

How I would answer this in an interview

"Policy-based authorisation is the model everything in ASP.NET Core authorisation is built on. Even [Authorize(Roles = ...)] becomes a policy under the hood. A policy has a name and a list of requirements. A requirement is just a data object implementing IAuthorizationRequirement, like 'must have the orders.read scope' or 'must be at least 18'. Handlers implement the logic. The evaluation rule is: every requirement in the policy must be satisfied, and a requirement is satisfied if any handler calls Succeed and none calls Fail. Claims-based authorisation is simply the built-in requirements: RequireClaim, RequireRole, RequireAuthenticatedUser and RequireAssertion for a quick lambda.

I register policies with AddAuthorizationBuilder().AddPolicy(...) and apply them with [Authorize(Policy = ...)] on controllers or RequireAuthorization("policy") on Minimal API endpoints. On Minimal APIs I put it on the route group, so /admin and everything under it gets the policy, and individual endpoints add more. The AuthorizationMiddleware runs after routing, reads the endpoint's metadata, combines it into one policy and evaluates it.

The thing people mix up is the default policy versus the fallback policy. The default policy is what a bare [Authorize] means; out of the box that's 'authenticated user'. The fallback policy is used when an endpoint has no authorisation metadata at all, and by default it is null, meaning anonymous access. I always set the fallback policy to RequireAuthenticatedUser, so a new endpoint someone forgot to protect is closed rather than open, and public endpoints such as health checks say AllowAnonymous explicitly. The senior line: make access denied the default, and make every exception visible in code review."


The pieces

Piece Role Example
AuthorizationPolicy Named list of requirements plus authentication schemes "CanApproveLoans"
IAuthorizationRequirement Data describing a rule new MinimumAgeRequirement(18)
IAuthorizationHandler Logic that calls Succeed or Fail Reads the birthdate claim
IAuthorizationService Evaluates a policy imperatively AuthorizeAsync(User, resource, "Policy")
AuthorizationMiddleware Evaluates endpoint metadata per request Returns 401 (challenge) or 403 (forbid)

Evaluation rules

Situation Result
Two requirements, both handled successfully Allowed
Two requirements, one not handled Denied
One requirement, two handlers, one succeeds Allowed (OR)
One requirement, one handler succeeds, another calls Fail() Denied
Not authenticated and policy denies Challenge: 401 or a login redirect
Authenticated and policy denies Forbid: 403

Default vs fallback

Policy Used when Out of the box
DefaultPolicy [Authorize] or RequireAuthorization() with no policy name Requires an authenticated user
FallbackPolicy Endpoint has no IAuthorizeData or IAllowAnonymous metadata null: anonymous allowed

Production example

On a [government grants] portal, setting FallbackPolicy = RequireAuthenticatedUser() and adding an endpoint-enumeration test found [7] endpoints that had shipped without any authorisation, including [an export endpoint]. After the change, new endpoints were closed by default and the pen test that quarter reported [zero] unauthenticated-access findings.

🔍 What the interviewer is checking

Checks whether the candidate understands the policy, requirement and handler model, its AND/OR evaluation, and how to make an ASP.NET Core app secure by default.

Green flags

  • Explains requirements as data and handlers as logic
  • Gets the evaluation rules right, including Fail() as a veto
  • Distinguishes DefaultPolicy from FallbackPolicy and sets the fallback
  • Uses route groups and AllowAnonymous deliberately

Red flags

  • Only knows [Authorize(Roles = ...)]
  • Writes if (User.IsInRole(...)) in every action
  • Thinks a missing [Authorize] means the endpoint is protected by default

📚 Learn in depth

1. From metadata to a decision

Request
  -> UseRouting          (endpoint selected, metadata attached)
  -> UseAuthentication   (HttpContext.User populated from the default scheme)
  -> UseAuthorization
       1. collect IAuthorizeData / IAuthorizationRequirementData / AuthorizationPolicy metadata
       2. none and no IAllowAnonymous?  -> FallbackPolicy (if set)
       3. AuthorizationPolicy.CombineAsync(provider, metadata) -> one policy
       4. IPolicyEvaluator.AuthenticateAsync (policy-specific schemes, if any)
       5. IAuthorizationService.AuthorizeAsync(user, resource: HttpContext, policy)
       6. success -> next ; fail + anonymous -> ChallengeAsync (401) ; fail + authenticated -> ForbidAsync (403)
  -> endpoint

The resource passed to handlers by the middleware is the HttpContext (endpoint routing), so a handler can read route values, but that isn't the same as real resource-based authorisation against a loaded entity.

2. Requirements and handlers

A requirement can be its own handler (AuthorizationHandler<TRequirement>, IAuthorizationRequirement), as the built-in ClaimsAuthorizationRequirement and RolesAuthorizationRequirement are. Custom handlers are registered in DI as IAuthorizationHandler; DefaultAuthorizationService runs every handler for the context, and each handler checks context.PendingRequirements for the requirements it understands.

AuthorizationOptions.InvokeHandlersAfterFailure is true by default, so handlers still run after one fails (useful for logging, not for short-circuiting costly checks).

3. RequireAssertion vs a real handler

RequireAssertion(ctx => ...) builds an AssertionRequirement with a lambda. It is fine for a one-off rule on claims. Once the rule needs a service (database, cache, clock), is reused, or needs a unit test, write a requirement and a handler.

4. Minimal APIs and route groups

RequireAuthorization adds AuthorizeAttribute (or a policy object) to endpoint metadata. Groups add metadata to every endpoint built from them, and metadata accumulates: a group policy plus an endpoint policy means both apply. AllowAnonymous() on an endpoint adds IAllowAnonymous, which wins over any authorisation metadata, including the group's.

api = MapGroup("/api").RequireAuthorization()             // DefaultPolicy
  admin = api.MapGroup("/admin").RequireAuthorization("Admin")
    MapDelete("/users/{id}")                              // Default + Admin
  MapGet("/status").AllowAnonymous()                      // anonymous wins

5. Policy providers

IAuthorizationPolicyProvider resolves policy names. The default provider reads AuthorizationOptions. A custom provider can build policies on the fly from the name (for example "Permission:orders.refund"), which is how dynamic permission policies are built without registering hundreds of policies. Since .NET 8, IAuthorizationRequirementData lets a custom attribute supply requirements directly, so [MinimumAge(18)] works without a custom provider.

Try it yourself

  1. Build an endpoint with a policy that has two requirements and show with tests that both must pass.
  2. Register two handlers for one requirement, make one call Fail(), and observe the result.
  3. Set a fallback policy, then write a test that enumerates EndpointDataSource.Endpoints and asserts every endpoint has either IAuthorizeData or IAllowAnonymous metadata.
  4. Turn on Microsoft.AspNetCore.Authorization debug logging and read why a request was denied.

💻 Code

Policies with built-in requirements, applied to Minimal API groups, with a secure-by-default fallback policy.

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

var builder = WebApplication.CreateBuilder(args);
builder.Services.AddAuthentication().AddJwtBearer();

builder.Services.AddAuthorizationBuilder()
    // Endpoints with no authorisation metadata now require a signed-in user.
    .SetFallbackPolicy(new AuthorizationPolicyBuilder().RequireAuthenticatedUser().Build())
    .AddPolicy("orders.read", p => p.RequireClaim("scope", "orders.read", "orders.write")) // any value
    .AddPolicy("orders.write", p => p.RequireClaim("scope", "orders.write"))
    .AddPolicy("StaffInAustralia", p => p
        .RequireRole("Staff")                                    // requirement 1
        .RequireAssertion(ctx =>                                // requirement 2 (AND)
            ctx.User.HasClaim(c => c.Type == "country" && c.Value == "AU")));

var app = builder.Build();
app.UseAuthentication();
app.UseAuthorization();

var orders = app.MapGroup("/orders").RequireAuthorization("orders.read");
orders.MapGet("/", () => Results.Ok(Array.Empty<object>()));
orders.MapPost("/", (CreateOrder cmd) => Results.Created($"/orders/1", cmd))
      .RequireAuthorization("orders.write");                 // group policy AND this policy

app.MapGet("/healthz", () => Results.Ok()).AllowAnonymous(); // explicit exception to the fallback
app.MapGet("/me", (ClaimsPrincipal user) => user.Identity!.Name); // covered by the fallback policy

app.Run();

public sealed record CreateOrder(string Sku, int Quantity);
// Imperative check when the decision depends on data you only have inside the handler.
app.MapPost("/reports/{id:int}/publish", async (int id, ClaimsPrincipal user,
    IAuthorizationService authz, CancellationToken ct) =>
{
    var result = await authz.AuthorizeAsync(user, "StaffInAustralia");
    return result.Succeeded ? Results.NoContent() : Results.Forbid();
});

⚠ Common mistakes

  • Mistake: Confusing DefaultPolicy with FallbackPolicy. Why it is wrong: changing the default policy doesn't protect endpoints that have no [Authorize] at all. Instead: set FallbackPolicy to require an authenticated user and use AllowAnonymous for public endpoints.
  • Mistake: Expecting a group's policy to be replaced by an endpoint's policy. Why it is wrong: authorisation metadata accumulates, so both policies apply. Instead: design groups so endpoint policies only add restrictions; use a separate group for different rules.
  • Mistake: Calling context.Fail() whenever a handler's condition isn't met. Why it is wrong: Fail vetoes the requirement even if another handler would succeed. Instead: simply don't call Succeed; reserve Fail for a definite deny such as a revoked account.
  • Mistake: Putting service calls or complex rules in RequireAssertion. Why it is wrong: lambdas can't take DI dependencies cleanly and are hard to test. Instead: a requirement plus a handler registered in DI.
  • Mistake: Registering hundreds of near-identical policies (one per permission). Why it is wrong: start-up code grows and is easy to get wrong. Instead: a custom IAuthorizationPolicyProvider or IAuthorizationRequirementData attribute.
  • Mistake: Writing authorisation checks inside endpoint bodies with if (!User.HasClaim(...)). Why it is wrong: the check is invisible to OpenAPI, tests and reviewers, and easy to forget. Instead: declarative policies on endpoints, imperative IAuthorizationService only when data is needed.
  • Mistake: Relying on RequireClaim("scope", "orders.read") when the token puts all scopes in one space-separated scp claim. Why it is wrong: the claim value is "orders.read orders.write", so the exact match fails. Instead: split scopes in claims transformation or use Microsoft.Identity.Web's RequireScope.

🏛 Senior insight: trade-offs

Policies are where authorisation becomes reviewable. I want every endpoint to declare a policy name that reads like a business capability, every policy registered in one place, and a test that fails the build when an endpoint has no metadata. The fallback policy is the single cheapest security improvement in most ASP.NET Core apps.

Option When it fits Cost When not to
RequireClaim / RequireRole Simple claim checks None Rules needing data or services
RequireAssertion One-off claim logic Hard to test and reuse Anything with dependencies
Requirement + handler Reusable, testable rules A class or two Trivial checks
Custom policy provider Dynamic or permission-style names Must cache built policies Small, fixed set of policies
IAuthorizationService in code Decision needs a loaded resource Easy to forget, so test it Coarse endpoint-level rules

Measure it: count endpoints by policy, check authorisation failure logs per policy in Application Insights, and alert on a spike of 403s after a deployment, which usually means a policy or claim mapping changed.

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions doing checks in a filter Why: Checks they know when an endpoint filter is the right place versus an authorisation policy
    How to answer

    An endpoint filter is the Minimal API equivalent of an MVC action filter: it wraps the handler invocation after routing and parameter binding, so it can see the bound arguments through EndpointFilterInvocationContext.Arguments, run code before and after the handler, change the result, or short-circuit by returning a result without calling next. You implement IEndpointFilter (or pass a lambda to AddEndpointFilter) and attach it to an endpoint or a route group. Order is an onion: filters run in the order added on the way in and reverse on the way out, with group filters outside endpoint filters. AddEndpointFilterFactory lets you inspect the handler once at start-up and skip the filter where it isn't needed. The trade-off: filters are precise and cheap but only wrap Minimal API handlers; global concerns stay in middleware.

  2. When: Candidate mentions RequireClaim or scopes Why: Checks where the claims that policies rely on actually come from
    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.

↩ Usually asked after

More in Authorization

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me