The Analogy: The Door Policy
A concert venue has two completely different jobs happening at the entrance, and they are often confused with each other. The first is the person checking identity documents: they look at your face, look at your card, and decide whether you are who you claim to be. They do not care which room you want to enter. Their entire job is answering one question — who are you? Once satisfied, they snap a wristband on you and wave you through. That is authentication.
The second job happens further inside. A steward at the foot of the balcony stairs glances at your wristband. Green means the floor only, gold means the balcony, black means backstage. The steward does not ask for your ID and would not know what to do with it — the wristband already encodes everything they need. Their job answers a completely different question — what are you allowed to do? That is authorization. Notice that the steward can turn you away even though the first person let you in. Being correctly identified and being permitted are separate outcomes, which is exactly why HTTP has two separate status codes: 401 Unauthorized means "I do not know who you are", and 403 Forbidden means "I know exactly who you are, and the answer is still no".
The wristband is the interesting part of the design. The ID check is expensive: it involves a human squinting at a document. So the venue does it once, then issues a cheap token that can be checked in a second at every other door. The wristband is tamper-evident — it has a hologram, and cutting it off destroys it — so a steward can trust it without phoning the front desk. It also expires: at the end of the night it is worthless. A JWT bearer token is that wristband, down to the details. Your credentials are checked once by a login endpoint or an identity provider, and in exchange you get a signed string. Every subsequent request presents the string, the server verifies the signature with a key, reads the claims printed on it, and never touches a user database at all.
The analogy also warns you about the failure modes. A wristband found on the floor works for whoever picks it up — a bearer token is exactly as dangerous, which is why it travels only over HTTPS and lives as short a life as you can tolerate. A wristband with the colour drawn on in marker is a forgery, and the hologram is what defeats it — that is the signature, and skipping the signature check is the single worst mistake in this topic. And a wristband that says "gold" is only meaningful because the venue decided gold means balcony; the token carries claims, but your application decides what those claims permit. The token says who you are; your policies say what that is worth.
Syntax or Core Structure
An ASP.NET Core application wires authentication in two steps: register a scheme with services, then place the two middlewares in the pipeline. Endpoints then opt in to protection with RequireAuthorization or the [Authorize] attribute.
The example below is a complete, self-contained program. It builds its own tokens so you can see all three interesting cases — no token, a good token, an expired token — without a separate identity server.
dotnet new web -o DoorPolicy
cd DoorPolicy
dotnet add package Microsoft.AspNetCore.Authentication.JwtBearer
dotnet add package System.IdentityModel.Tokens.Jwt
using System.IdentityModel.Tokens.Jwt;
using System.Net.Http.Headers;
using System.Security.Claims;
using System.Text;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.IdentityModel.Tokens;
const string Issuer = "https://door.example";
const string Audience = "orders-api";
SymmetricSecurityKey signingKey = new SymmetricSecurityKey(
Encoding.UTF8.GetBytes("demo-signing-key-at-least-32-bytes-long"));
SigningCredentials credentials = new SigningCredentials(signingKey, SecurityAlgorithms.HmacSha256);
WebApplicationBuilder builder = WebApplication.CreateBuilder(args);
builder.Logging.ClearProviders();
builder.WebHost.UseUrls("http://localhost:5218");
// 1. Register the scheme: how a token is turned into a ClaimsPrincipal.
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
options.MapInboundClaims = false; // keep the names the token actually used
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = true,
ValidIssuer = Issuer,
ValidateAudience = true,
ValidAudience = Audience,
ValidateIssuerSigningKey = true, // never turn this off
IssuerSigningKey = signingKey,
ValidateLifetime = true,
ClockSkew = TimeSpan.Zero, // the default grants 5 extra minutes
NameClaimType = "sub",
RoleClaimType = "role"
};
});
builder.Services.AddAuthorization();
WebApplication app = builder.Build();
// 2. Order matters: identify first, then enforce.
app.UseAuthentication();
app.UseAuthorization();
app.MapGet("/public", () => "anyone may read this");
// 3. Opt the endpoint in. Without this line the endpoint is public.
app.MapGet("/orders", (ClaimsPrincipal user) => new WhoAmI(
user.Identity?.Name ?? "?",
user.FindAll("role").Select(claim => claim.Value).Order().ToArray()))
.RequireAuthorization();
await app.StartAsync();
using HttpClient client = new HttpClient { BaseAddress = new Uri("http://localhost:5218") };
string good = Token("ada", new[] { "buyer" }, TimeSpan.FromMinutes(10));
string stale = Token("ada", new[] { "buyer" }, TimeSpan.FromMinutes(-5));
await Call("public, no token", "/public", null);
await Call("orders, no token", "/orders", null);
await Call("orders, good token", "/orders", good);
await Call("orders, expired", "/orders", stale);
await app.StopAsync();
string Token(string subject, string[] roles, TimeSpan lifetime)
{
List<Claim> claims = new List<Claim> { new Claim("sub", subject) };
foreach (string role in roles)
{
claims.Add(new Claim("role", role));
}
JwtSecurityToken token = new JwtSecurityToken(
issuer: Issuer,
audience: Audience,
claims: claims,
notBefore: DateTime.UtcNow.AddMinutes(-1),
expires: DateTime.UtcNow.Add(lifetime),
signingCredentials: credentials);
return new JwtSecurityTokenHandler().WriteToken(token);
}
async Task Call(string label, string path, string? token)
{
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, path);
if (token is not null)
{
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token);
}
HttpResponseMessage response = await client.SendAsync(request);
string body = await response.Content.ReadAsStringAsync();
Console.WriteLine($"{label,-20} {(int)response.StatusCode} {Challenge(response)} " +
(body.Length == 0 ? "(no body)" : body));
}
static string Challenge(HttpResponseMessage response)
{
// Bearer error="invalid_token", error_description="The token expired at ..."
string? header = response.Headers.WwwAuthenticate.FirstOrDefault()?.ToString();
if (header is null)
{
return "-";
}
string[] parts = header.Split('"');
return parts.Length > 1 ? "error=" + parts[1] : "Bearer";
}
record WhoAmI(string Name, string[] Roles);
Output:
public, no token 200 - anyone may read this
orders, no token 401 Bearer (no body)
orders, good token 200 - {"name":"ada","roles":["buyer"]}
orders, expired 401 error=invalid_token (no body)
Four lines, four lessons. /public is reachable with no credentials at all because it never called RequireAuthorization. /orders with no token returns 401 and a bare WWW-Authenticate: Bearer header, which is the server politely naming the scheme it expects. The good token produces a ClaimsPrincipal whose Name is the sub claim — that mapping came from NameClaimType, not from magic. The expired token fails with error="invalid_token", and because ClockSkew was set to zero it fails immediately rather than five minutes later.
Note what the program never had to do: no database lookup, no session store, no shared state between the token issuer and the endpoint. The signature is the only trust anchor.
Technical Depth: Schemes, Claims and Policies
The pipeline order is not negotiable
Authentication reads credentials and attaches a ClaimsPrincipal to HttpContext.User. Authorization inspects that principal against the endpoint's requirements. If you register them in the wrong order, the authorization middleware sees an anonymous user on every request and rejects everything.
| Middleware | Registered as | Does | Must come after |
|---|---|---|---|
| Routing | UseRouting | picks the endpoint, so its metadata is known | nothing |
| Authentication | UseAuthentication | sets HttpContext.User | routing |
| Authorization | UseAuthorization | reads endpoint metadata, enforces policies | authentication |
| Endpoint | MapGet and friends | runs your handler | authorization |
A WebApplication adds UseAuthentication and UseAuthorization for you when the matching services are registered, and it inserts them in the right place. Writing them explicitly is still worth doing: the moment you add your own middleware that reads HttpContext.User, you need to know where the line is.
Schemes: one application, several front doors
A scheme is a named recipe for turning a request into a principal. AddJwtBearer reads the Authorization header; AddCookie reads an encrypted cookie; AddOpenIdConnect redirects to an identity provider. Each has a name, and the first one registered becomes the default.
builder.Services.AddAuthentication("web")
.AddCookie("web", options =>
{
options.Cookie.HttpOnly = true; // JavaScript cannot read it
options.Cookie.SameSite = SameSiteMode.Lax;
options.Cookie.SecurePolicy = CookieSecurePolicy.Always;
options.SlidingExpiration = true;
options.ExpireTimeSpan = TimeSpan.FromHours(8);
})
.AddJwtBearer("api", options => { /* token validation as above */ });
builder.Services.AddAuthorization(options =>
{
// Accept either front door for endpoints that do not say otherwise.
options.DefaultPolicy = new AuthorizationPolicyBuilder("web", "api")
.RequireAuthenticatedUser()
.Build();
});
An endpoint can name a scheme explicitly with [Authorize(AuthenticationSchemes = "api")] or RequireAuthorization(new AuthorizeAttribute { AuthenticationSchemes = "api" }). Browser applications usually want cookies; machine clients and mobile apps usually want bearer tokens; an application that serves both keeps both schemes and stops arguing about it.
What a principal actually is
ClaimsPrincipal one user, as this request sees them
+-- ClaimsIdentity one proof of identity (one scheme)
+-- Claim Type = "role", Value = "buyer", Issuer = "..."
A principal can hold several identities — that is how "signed in with cookies and presenting an API key" is modelled. IsAuthenticated is a property of an identity, not of the principal, and User.Identity returns only the primary one. Two consequences bite people:
User.Identity.IsAuthenticatedisfalsefor an anonymous request butUseris not null — ASP.NET Core always supplies an empty principal. Null-checkingUseris pointless; checkIsAuthenticated.User.IsInRole("admin")reads whichever claim type the identity was told is its role type. If the token said"role"and the identity thinks roles live in the longClaimTypes.RoleURI, the check silently returnsfalse. That is why the example setRoleClaimTypeexplicitly.
The claim-type mapping is a genuine trap. By default JwtBearer rewrites short JWT names into legacy SOAP-era URIs: sub becomes http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier. Setting MapInboundClaims = false turns the rewriting off, and then what you see in the token is what you find in the principal.
Roles, claims and policies
There are three ways to express a rule, and they are not equally good.
| Mechanism | Written as | Reads | Use when |
|---|---|---|---|
| Role | [Authorize(Roles = "admin")] | one role claim | coarse, stable job titles |
| Claim | policy.RequireClaim("scope", "orders.write") | any claim type and value | a capability the token grants |
| Policy | [Authorize(Policy = "refunds")] | arbitrary code | anything with a rule behind it |
| Requirement | policy.AddRequirements(new OwnerRequirement()) | your handler decides | the rule depends on data |
Prefer named policies over sprinkling role strings through controllers. A policy is declared once, so when "who may issue a refund" changes, you edit one line instead of grepping for "admin".
builder.Services.AddAuthorization(options =>
{
options.AddPolicy("refunds", policy => policy.RequireRole("admin"));
options.AddPolicy("orders.write", policy => policy.RequireClaim("scope", "orders.write"));
options.AddPolicy("verified-adult", policy => policy
.RequireAuthenticatedUser()
.RequireClaim("age_verified", "true")
.RequireAssertion(context => context.User.HasClaim(claim =>
claim.Type == "country" && claim.Value != "XX")));
});
Requirements inside one policy are AND-ed: every one must succeed. To express OR, either use RequireAssertion or write a requirement whose handler succeeds on any of several conditions. Applying two [Authorize] attributes also ANDs them, which surprises people who expect the second to widen access.
A requirement with a handler
When the rule needs data — ownership, tenancy, an amount limit — model it as a requirement plus a handler. The requirement is a marker holding parameters; the handler contains the logic and is resolved from DI, so it can inject anything.
sealed class AmountLimitRequirement : IAuthorizationRequirement
{
public AmountLimitRequirement(int maximumMinorUnits) => MaximumMinorUnits = maximumMinorUnits;
public int MaximumMinorUnits { get; }
}
sealed class AmountLimitHandler : AuthorizationHandler<AmountLimitRequirement, Refund>
{
protected override Task HandleRequirementAsync(
AuthorizationHandlerContext context, AmountLimitRequirement requirement, Refund resource)
{
if (resource.AmountMinorUnits <= requirement.MaximumMinorUnits || context.User.IsInRole("admin"))
{
context.Succeed(requirement); // no Fail() call: absence of Succeed is enough
}
return Task.CompletedTask;
}
}
Register handlers as IAuthorizationHandler: builder.Services.AddSingleton<IAuthorizationHandler, AmountLimitHandler>(). Several handlers may target the same requirement, and any of them calling Succeed satisfies it — that is the supported way to express OR across handlers. context.Fail() is different in kind: it vetoes the whole policy even if another handler succeeded, so reserve it for hard blocks such as a suspended account.
Resource-based authorization
Attributes and RequireAuthorization run before your handler, so they cannot see the row you are about to return. "May this user read this order?" therefore has to be asked from inside the handler, once the resource is loaded, using IAuthorizationService.
AuthorizationResult result = await authorization.AuthorizeAsync(user, order, "order-owner");
if (!result.Succeeded)
{
return Results.Forbid();
}
There is a second-order concern here: leaking existence. Returning 403 for someone else's order tells the caller the order exists; returning 404 tells them nothing. For public identifiers 403 is friendlier, for sensitive ones 404 is safer, and the choice belongs to the product, not the framework.
401 versus 403
| Situation | Status | Response detail | Caused by |
|---|---|---|---|
| No credentials | 401 | WWW-Authenticate: Bearer | ChallengeAsync |
| Expired, tampered or wrong-audience token | 401 | error="invalid_token" | validation failure |
| Valid token, rule not satisfied | 403 | usually no body | ForbidAsync |
| Valid token, no such resource | 404 | your choice of body | your handler |
A retry loop that refreshes the token on 401 and gives up on 403 is the correct client behaviour, and it only works if your server distinguishes the two properly. Returning 401 for a failed permission check sends clients into a pointless refresh spiral.
Validating a token: the settings that matter
| Setting | Default | Why you care |
|---|---|---|
RequireSignedTokens | true | refuses unsigned tokens; the signature is the only trust anchor |
IssuerSigningKey / Authority | none | the key the signature is checked against; without one nothing validates |
ValidateIssuer / ValidIssuer | true | stops a token minted for another system being replayed at yours |
ValidateAudience / ValidAudience | true | stops your API accepting a token meant for a different API |
ValidateLifetime | true | rejects expired tokens; nbf is checked too |
ClockSkew | 5 minutes | a token is accepted for 5 minutes past exp unless you shrink it |
NameClaimType / RoleClaimType | ClaimTypes.* | which claim Name and IsInRole read |
RequireExpirationTime | true | refuses tokens with no exp at all |
In production you rarely paste a signing key into the API. Instead you point at the identity provider and let the handler fetch and cache its public keys, rotating them automatically:
.AddJwtBearer(options =>
{
options.Authority = "https://login.example.com"; // downloads /.well-known/openid-configuration
options.Audience = "orders-api";
options.RequireHttpsMetadata = true; // false only on a developer machine
});
That is asymmetric signing: the provider holds the private key, your API only ever sees public keys, and a compromise of your API cannot mint tokens. Symmetric HmacSha256 keys, as used in the examples here, must be shared with every validator — acceptable inside one deployment, dangerous across teams.
Cookies or tokens
| Concern | Cookie | Bearer token |
|---|---|---|
| Sent by the browser automatically | yes | no, the client attaches it |
| CSRF exposure | yes, needs antiforgery | no, headers are not auto-sent |
| Cross-origin and mobile clients | awkward | natural |
| Revocation | delete the server session or rotate the key | hard; keep lifetimes short |
| Size on every request | small | often 1 KB or more |
| Readable by JavaScript | not if HttpOnly | yes if stored in localStorage |
The "store the JWT in localStorage" pattern is popular and is the weakest of the options: any script injected into your page can read it. For a browser-only application, cookies with HttpOnly, Secure, SameSite and antiforgery tokens remain the safer default.
Real World Example: Three Doors, One Wristband
A small shop API has three doors with three different policies. The catalogue is open to the street. An order may be read by the customer who placed it, or by staff. A refund may only be issued by staff. Two of those rules cannot be expressed by an attribute alone, because one of them depends on the row being returned.
The program below runs the host and the client together and walks eleven requests through the door: anonymous callers, the right customer, the wrong customer, an administrator, a missing order, an expired token, and a token signed with a key the server has never seen.
using System.IdentityModel.Tokens.Jwt;
using System.Net.Http.Headers;
using System.Security.Claims;
using System.Text;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Authorization;
using Microsoft.IdentityModel.Tokens;
const string Issuer = "https://door.example";
const string Audience = "shop-api";
SymmetricSecurityKey serverKey = new SymmetricSecurityKey(
Encoding.UTF8.GetBytes("shop-signing-key-at-least-32-bytes-long"));
SymmetricSecurityKey attackerKey = new SymmetricSecurityKey(
Encoding.UTF8.GetBytes("attacker-key-also-at-least-32-bytes-x"));
Dictionary<int, OrderRecord> orders = new Dictionary<int, OrderRecord>
{
[1] = new OrderRecord(1, "ada", 750),
[2] = new OrderRecord(2, "grace", 1290)
};
WebApplicationBuilder builder = WebApplication.CreateBuilder(args);
builder.Logging.ClearProviders();
builder.WebHost.UseUrls("http://localhost:5219");
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
options.MapInboundClaims = false;
options.TokenValidationParameters = new TokenValidationParameters
{
ValidIssuer = Issuer,
ValidAudience = Audience,
IssuerSigningKey = serverKey,
ClockSkew = TimeSpan.Zero,
NameClaimType = "sub",
RoleClaimType = "role"
};
});
builder.Services.AddAuthorization(options =>
{
options.AddPolicy("refunds", policy => policy.RequireRole("admin"));
options.AddPolicy("order-owner", policy => policy.AddRequirements(new OwnerOrAdminRequirement()));
});
builder.Services.AddSingleton<IAuthorizationHandler, OwnerOrAdminHandler>();
WebApplication app = builder.Build();
app.UseAuthentication();
app.UseAuthorization();
// Door 1: open to the street.
app.MapGet("/catalogue", () => "hoodie 750, mug 400");
// Door 2: authenticated, then a rule that needs the row itself.
app.MapGet("/orders/{id:int}", async (int id, ClaimsPrincipal user, IAuthorizationService authorization) =>
{
if (!orders.TryGetValue(id, out OrderRecord? order))
{
return Results.NotFound();
}
AuthorizationResult decision = await authorization.AuthorizeAsync(user, order, "order-owner");
return decision.Succeeded ? Results.Ok(order) : Results.Forbid();
}).RequireAuthorization();
// Door 3: staff only, decided before the handler runs.
app.MapPost("/orders/{id:int}/refund", (int id) => $"refund queued for order {id}")
.RequireAuthorization("refunds");
await app.StartAsync();
using HttpClient client = new HttpClient { BaseAddress = new Uri("http://localhost:5219") };
string ada = Token("ada", new[] { "buyer" }, TimeSpan.FromMinutes(10), serverKey);
string grace = Token("grace", new[] { "buyer" }, TimeSpan.FromMinutes(10), serverKey);
string root = Token("root", new[] { "admin", "buyer" }, TimeSpan.FromMinutes(10), serverKey);
string expiredAda = Token("ada", new[] { "buyer" }, TimeSpan.FromMinutes(-5), serverKey);
string forgedRoot = Token("root", new[] { "admin" }, TimeSpan.FromMinutes(10), attackerKey);
await Call("catalogue, anonymous", HttpMethod.Get, "/catalogue", null);
await Call("order 1, anonymous", HttpMethod.Get, "/orders/1", null);
await Call("order 1, ada (owner)", HttpMethod.Get, "/orders/1", ada);
await Call("order 2, ada", HttpMethod.Get, "/orders/2", ada);
await Call("order 2, grace (owner)", HttpMethod.Get, "/orders/2", grace);
await Call("order 1, root (admin)", HttpMethod.Get, "/orders/1", root);
await Call("order 9, ada", HttpMethod.Get, "/orders/9", ada);
await Call("refund 1, ada", HttpMethod.Post, "/orders/1/refund", ada);
await Call("refund 1, root", HttpMethod.Post, "/orders/1/refund", root);
await Call("order 1, ada expired", HttpMethod.Get, "/orders/1", expiredAda);
await Call("order 1, forged admin", HttpMethod.Get, "/orders/1", forgedRoot);
await app.StopAsync();
string Token(string subject, string[] roles, TimeSpan lifetime, SecurityKey key)
{
List<Claim> claims = new List<Claim> { new Claim("sub", subject) };
foreach (string role in roles)
{
claims.Add(new Claim("role", role));
}
JwtSecurityToken token = new JwtSecurityToken(
issuer: Issuer,
audience: Audience,
claims: claims,
notBefore: DateTime.UtcNow.AddMinutes(-1),
expires: DateTime.UtcNow.Add(lifetime),
signingCredentials: new SigningCredentials(key, SecurityAlgorithms.HmacSha256));
return new JwtSecurityTokenHandler().WriteToken(token);
}
async Task Call(string label, HttpMethod method, string path, string? token)
{
HttpRequestMessage request = new HttpRequestMessage(method, path);
if (token is not null)
{
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token);
}
HttpResponseMessage response = await client.SendAsync(request);
string body = await response.Content.ReadAsStringAsync();
Console.WriteLine($"{label,-22} {(int)response.StatusCode} {Challenge(response)} " +
(body.Length == 0 ? "(no body)" : body));
}
static string Challenge(HttpResponseMessage response)
{
string? header = response.Headers.WwwAuthenticate.FirstOrDefault()?.ToString();
if (header is null)
{
return "-";
}
string[] parts = header.Split('"');
return parts.Length > 1 ? "error=" + parts[1] : "Bearer";
}
sealed class OwnerOrAdminRequirement : IAuthorizationRequirement { }
sealed class OwnerOrAdminHandler : AuthorizationHandler<OwnerOrAdminRequirement, OrderRecord>
{
protected override Task HandleRequirementAsync(
AuthorizationHandlerContext context,
OwnerOrAdminRequirement requirement,
OrderRecord resource)
{
string? subject = context.User.FindFirst("sub")?.Value;
if (context.User.IsInRole("admin") ||
string.Equals(subject, resource.Owner, StringComparison.Ordinal))
{
context.Succeed(requirement);
}
return Task.CompletedTask;
}
}
record OrderRecord(int Id, string Owner, int TotalMinorUnits);
Output:
catalogue, anonymous 200 - hoodie 750, mug 400
order 1, anonymous 401 Bearer (no body)
order 1, ada (owner) 200 - {"id":1,"owner":"ada","totalMinorUnits":750}
order 2, ada 403 - (no body)
order 2, grace (owner) 200 - {"id":2,"owner":"grace","totalMinorUnits":1290}
order 1, root (admin) 200 - {"id":1,"owner":"ada","totalMinorUnits":750}
order 9, ada 404 - (no body)
refund 1, ada 403 - (no body)
refund 1, root 200 - refund queued for order 1
order 1, ada expired 401 error=invalid_token (no body)
order 1, forged admin 401 error=invalid_token (no body)
Read the status column as two separate stories. Lines 2, 10 and 11 are 401: the server does not know who is calling, because there was no token, because the token had expired, or because the signature did not check out. A well-written client responds to those by refreshing its credentials and retrying. Lines 4 and 8 are 403: the server knows exactly who is calling — ada, a buyer in good standing — and the answer is still no. Refreshing the token would change nothing, and a client that retries on 403 has built itself an infinite loop.
Line 11 is the one worth staring at. That token says sub: root and role: admin, and every permission check in this codebase would have waved it through — IsInRole("admin") would have returned true, the refunds policy would have passed, the ownership handler would have short-circuited on the first condition. The only thing that stopped it was that the signature was produced with attackerKey and verified against serverKey. Claims inside a bearer token are attacker-controlled input until the signature says otherwise; that is the whole reason the historical alg: none and HMAC-versus-RSA confusion attacks were so severe. Everything downstream of validation is built on that one check.
Lines 3 to 6 all hit the same endpoint and the same handler, and produce three different outcomes. ada may read order 1 and not order 2; grace may read order 2; root may read either. No attribute could have decided this, because the decision needs the Owner field of the row, which does not exist until the handler has looked it up. That is exactly the seam IAuthorizationService fills: the coarse "must be signed in" check runs in middleware, and the fine "must be yours" check runs after the load, both of them still expressed as a named policy rather than an if buried in a handler.
Line 7 encodes a policy decision that is easy to make by accident. The handler checks existence first, so a caller who asks for a non-existent order gets 404 while a caller who asks for someone else's gets 403 — which means the response tells them that order 2 exists. For a shop that is harmless. For a system where identifiers are guessable and their existence is sensitive, swap the order: authorize first, and return 404 when the check fails, so "not yours" and "not here" are indistinguishable from outside.
Common Mistakes
- Registering the middlewares in the wrong order.
UseAuthorizationbeforeUseAuthenticationmeans every request is evaluated as anonymous, so protected endpoints return 401 no matter how good the token is. - Assuming a route is protected because of its name.
/api/admin/usersis public until something callsRequireAuthorizationor[Authorize]. Naming conventions enforce nothing; use a fallback policy if you want default-deny. - Reading claims from a token you have not validated. Decoding a JWT is not verifying it — the payload is base64, not ciphertext. Any code path that trusts
suborrolewithout a signature check has no security at all. - Weakening validation to make development easier.
ValidateIssuer = false,ValidateAudience = falseor a hand-rolledSignatureValidatorthat returns the token unchecked all tend to survive the trip to production. - Leaving
ClockSkewat its 5 minute default and then debugging "expired tokens still work". They do, for five more minutes, by design. Set it to zero or a few seconds when you are testing expiry. - Being defeated by claim-type mapping.
RequireRole("admin")returns false when the token carriesrolebut the identity'sRoleClaimTypeis the longClaimTypes.RoleURI. SetRoleClaimType,NameClaimTypeandMapInboundClaimsdeliberately.
- Returning 401 for a permission failure. Clients treat 401 as "refresh and retry"; if the real problem is a missing role, they will loop forever. Authenticated but not allowed is always 403.
- Expecting two
[Authorize]attributes to widen access. Requirements and attributes are combined with AND, so adding[Authorize(Roles = "support")]beside[Authorize(Roles = "admin")]demands both roles. Express OR inside one policy. - Treating a token as a secret you can be careless with. Logging the
Authorizationheader, echoing tokens in error messages, or storing them inlocalStorageall hand over a working wristband to whoever reads them. - Issuing long-lived tokens with no revocation story. A stateless token cannot be un-issued. If a 24 hour token leaks, it works for 24 hours; short lifetimes plus refresh tokens are the standard answer.
Best Practices
- Make default-deny the shape of your application: set
options.FallbackPolicy = new AuthorizationPolicyBuilder().RequireAuthenticatedUser().Build()and mark the handful of open endpoints withAllowAnonymous. Forgetting an attribute then fails closed instead of open. - Name your rules.
[Authorize(Policy = "refunds")]survives an org chart change;[Authorize(Roles = "admin,finance,support-lead")]scattered across forty files does not. - In production, prefer
Authoritywith asymmetric keys over a sharedIssuerSigningKey. Your API then holds no key capable of minting tokens, and key rotation happens without a deployment. - Keep access tokens short — minutes, not hours — and let refresh tokens carry the long-lived risk, where they can be revoked server-side.
- Put data-dependent rules behind
IAuthorizationServiceand a requirement handler rather than inlineifstatements, so the rule is testable in isolation and reusable from a second endpoint. - For browser clients, use
HttpOnly,Secure,SameSitecookies plus antiforgery tokens, and keep bearer tokens for machine and mobile callers. - Log authorization failures with the subject, the policy name and the resource identifier — never the token itself. Those three fields are what turns "some 403s in production" into a diagnosis.
- Test the door, not just the lock: integration tests with a test authentication handler that assert 401 for anonymous, 403 for the wrong role and 200 for the right one catch the endpoint that quietly lost its
RequireAuthorizationin a refactor.
Practice Exercises
- Take the syntax example and add a
/whoamiendpoint that returns every claim as a sortedtype=valuelist. Then removeMapInboundClaims = falseand run it again, and write down which claim types changed and whyRoleClaimTypehad to be adjusted to keepIsInRoleworking. - Add a
"large-refund"policy backed by anAmountLimitRequirementof 1000 minor units and a handler that also succeeds for theadminrole. Wire it into the refund endpoint with a resource-based check, then prove with four calls that a buyer may refund 750 but not 1290, while an administrator may refund both. - Reverse the existence-leak decision in the real world example: authorize before loading, and return 404 instead of 403 when the ownership check fails. Verify that
order 2, adaandorder 9, adanow produce identical responses, and note what you lost in debuggability. - Write a second scheme called
"internal"that authenticates on a shared header value, register it alongside the JWT scheme, and give one endpoint a policy that accepts either scheme while the rest accept only JWTs. Confirm with three requests that the header works on the shared endpoint and is rejected everywhere else.