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.
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.
[Authorize(Policy = "...")] or RequireAuthorization("...") on Minimal API endpoints and MapGroup.[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.
"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 implementingIAuthorizationRequirement, 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 callsSucceedand none callsFail. Claims-based authorisation is simply the built-in requirements:RequireClaim,RequireRole,RequireAuthenticatedUserandRequireAssertionfor a quick lambda.I register policies with
AddAuthorizationBuilder().AddPolicy(...)and apply them with[Authorize(Policy = ...)]on controllers orRequireAuthorization("policy")on Minimal API endpoints. On Minimal APIs I put it on the route group, so/adminand everything under it gets the policy, and individual endpoints add more. TheAuthorizationMiddlewareruns 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 toRequireAuthenticatedUser, so a new endpoint someone forgot to protect is closed rather than open, and public endpoints such as health checks sayAllowAnonymousexplicitly. The senior line: make access denied the default, and make every exception visible in code review."
| 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) |
| 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 |
| 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 |
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.
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
Fail() as a vetoDefaultPolicy from FallbackPolicy and sets the fallbackAllowAnonymous deliberatelyRed flags
[Authorize(Roles = ...)]if (User.IsInRole(...)) in every action[Authorize] means the endpoint is protected by defaultRequest
-> 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.
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).
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.
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
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.
Fail(), and observe the result.EndpointDataSource.Endpoints and asserts every endpoint has either IAuthorizeData or IAllowAnonymous metadata.Microsoft.AspNetCore.Authorization debug logging and read why a request was denied.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();
});
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.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.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.IAuthorizationPolicyProvider or IAuthorizationRequirementData attribute.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.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.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.
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.
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.
Last updated 23 Nov 2026.