Authentication vs authorisation and the ASP.NET Core authentication model: schemes, handlers, ClaimsPrincipal, challenge vs forbid, and middleware order.
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.
"Authentication is proving identity: the request carries a cookie, a bearer token or an API key, and the server works out who is calling. Authorisation comes after: given that identity, is this caller allowed to do this action on this resource? The HTTP status codes follow the same split: 401 means 'I don't know who you are', 403 means 'I know who you are, and the answer is no'.
In ASP.NET Core, authentication is organised around schemes.
AddAuthentication().AddCookie().AddJwtBearer()registers named schemes, each backed by a handler. On every request,UseAuthenticationasks the default scheme's handler to authenticate; if it succeeds, the handler returns anAuthenticationTicketholding aClaimsPrincipal, and the middleware setsHttpContext.User. It never rejects a request by itself; an anonymous request just carries an empty principal. ThenUseAuthorizationlooks at the endpoint chosen by routing, reads its[Authorize]orRequireAuthorization()metadata, evaluates the policy, and if it fails callsChallengeAsync(no identity) orForbidAsync(identity but not allowed) on the scheme, and the handler turns that into a 401, a 403 or a redirect.The mistake I see is getting the middleware order wrong or registering authorisation in the wrong place: put
UseAuthorizationbeforeUseAuthentication, or beforeUseRouting, and the decision is made with an anonymous user or without endpoint metadata. The senior point is simple: authentication only establishes facts about the caller; every security decision happens in authorisation, close to the endpoint."
| Authentication | Authorisation | |
|---|---|---|
| Question | Who are you? | What may you do? |
| Input | Cookie, bearer token, API key, client certificate | ClaimsPrincipal + endpoint + resource |
| ASP.NET Core piece | IAuthenticationHandler, UseAuthentication |
IAuthorizationService, policies, UseAuthorization |
| Failure | Challenge: 401 (API) or redirect to login (web) | Forbid: 403 (API) or access-denied page (web) |
| Term | Meaning |
|---|---|
| Scheme | A name ("Cookies", "Bearer") bound to a handler and its options |
| Handler | Implements AuthenticateAsync, ChallengeAsync, ForbidAsync (and sign-in/out for cookies) |
ClaimsPrincipal |
The user: one or more ClaimsIdentity objects, each a bag of claims (sub, name, role) |
| Default scheme | Used by UseAuthentication and by [Authorize] without a scheme |
| Challenge / Forbid | What the scheme does when authorisation fails for an anonymous / authenticated user |
UseExceptionHandler -> UseHttpsRedirection -> UseRouting -> UseCors
-> UseAuthentication -> UseAuthorization -> (rate limiter, antiforgery) -> endpoints
WebApplication adds routing, authentication and authorisation for you when the services are registered, but as soon as you call UseRouting or UseCors yourself you should place the auth calls explicitly so the order is obvious in code review.
In a [company] API, a new route group was mapped without RequireAuthorization() and the team had no fallback policy, so 6 endpoints were anonymous for [two weeks]. We added FallbackPolicy = RequireAuthenticatedUser() so every endpoint is protected unless it opts out with [AllowAnonymous], plus an integration test that calls every endpoint without a token and expects 401: [0] anonymous endpoints have slipped through since.
Checks that the candidate separates identity from permission and understands the concrete ASP.NET Core model rather than just decorating controllers with [Authorize].
Green flags
ClaimsPrincipal and does not block requests itselfRed flags
UseAuthentication rejects invalid tokensHttpContext.User comes fromAuthentication does not decide anything; it produces facts. The output is an AuthenticateResult: success with an AuthenticationTicket (principal + properties + scheme), no result (no credential present), or failure (credential present but invalid, expired or tampered).
Request --> handler.AuthenticateAsync()
|-- Success(ticket) -> HttpContext.User = ticket.Principal
|-- NoResult -> HttpContext.User = anonymous principal
'-- Fail(reason) -> anonymous principal + logged reason
A failed token does not stop the request. That is deliberate: an endpoint marked [AllowAnonymous] should still work for a caller with an expired cookie.
Kestrel -> ... -> UseRouting (endpoint selected, metadata available)
-> UseAuthentication (sets User from the default scheme)
-> UseAuthorization (reads [Authorize], evaluates policies)
|-- allowed -> endpoint runs
|-- no identity -> ChallengeAsync(scheme) -> 401 / redirect
'-- denied -> ForbidAsync(scheme) -> 403 / redirect
UseAuthorization needs routing to have picked an endpoint, because the [Authorize] attribute is endpoint metadata. Before routing there is nothing to read.
AddAuthentication("Bearer") sets the default scheme; since .NET 7, if exactly one scheme is registered it becomes the default automatically. Each AddXxx call registers options and a handler type. Handlers derive from AuthenticationHandler<TOptions> and are created per request, so they can use scoped services.
You can split the defaults: DefaultAuthenticateScheme, DefaultChallengeScheme (OpenID Connect redirects to the identity provider), DefaultSignInScheme (cookies persist the result). That split is exactly how a typical web app with an external login works.
A claim is a typed statement about the subject, issued by someone: sub=42, [email protected], role=Admin. ClaimsPrincipal.IsInRole looks at the identity's RoleClaimType, and User.Identity.Name reads its NameClaimType, which is why claim mapping (covered in the claims question) matters.
For APIs the challenge is a 401 with a WWW-Authenticate header; for cookie-based web apps it is a 302 to the login page. Since .NET 10, the cookie handler returns 401/403 instead of redirecting for known API endpoints (for example [ApiController] actions and Minimal API endpoints returning JSON), which removes an old trap where an API call got an HTML login page with status 200.
[Authorize] endpoint and JWT bearer; call it with no token and inspect the 401 and WWW-Authenticate header.UseAuthorization above UseAuthentication and observe that a valid token now gets 401."Microsoft.AspNetCore.Authentication": "Debug" logging and read why a token failed.User.Claims as JSON and compare the claims for two schemes.WebApplicationFactory that asserts every endpoint returns 401 anonymously, except an allow-list.A minimal API with one authentication scheme, a fallback policy and the middleware in the right order.
// Program.cs (.NET 10, nullable enabled)
using System.Security.Claims;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Authorization;
var builder = WebApplication.CreateBuilder(args);
builder.Services
.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) // default scheme
.AddJwtBearer(options =>
{
// Issuer metadata and signing keys come from the identity provider.
options.Authority = builder.Configuration["Auth:Authority"];
options.Audience = builder.Configuration["Auth:Audience"];
});
builder.Services.AddAuthorizationBuilder()
// Every endpoint requires a signed-in user unless it opts out.
.SetFallbackPolicy(new AuthorizationPolicyBuilder().RequireAuthenticatedUser().Build());
var app = builder.Build();
app.UseHttpsRedirection();
app.UseAuthentication(); // sets HttpContext.User
app.UseAuthorization(); // decides, using endpoint metadata
app.MapGet("/health", () => Results.Ok()).AllowAnonymous();
app.MapGet("/me", (ClaimsPrincipal user) => new
{
Id = user.FindFirstValue(ClaimTypes.NameIdentifier),
Name = user.Identity?.Name,
Claims = user.Claims.Select(c => new { c.Type, c.Value })
});
app.Run();
UseAuthorization() before UseAuthentication(), or before routing. Why it is wrong: the policy is evaluated against an anonymous user (valid callers get 401) or without endpoint metadata, and in custom pipelines a misplaced branch can serve endpoints that never pass through authorisation at all. Instead: authentication first, then authorisation, both after routing and CORS, and an integration test that proves protected endpoints return 401 anonymously.UseAuthentication to block bad tokens. Why it is wrong: it only sets User; an invalid token simply results in an anonymous request, so an endpoint without [Authorize] serves data to anyone. Instead: protect endpoints with [Authorize], RequireAuthorization() or a fallback policy.[Authorize] on every controller and route group. Why it is wrong: one forgotten attribute exposes an endpoint anonymously, which under the Privacy Act can become a notifiable breach if personal information is returned. Instead: set a fallback policy and opt out explicitly with [AllowAnonymous].[AllowAnonymous] and policies. Instead: handlers produce claims; policies decide.[Authorize] uses only the default scheme, so a cookie user is rejected by a JWT default (or vice versa), and a policy scheme that forwards on a header can accept a weaker scheme than intended. Instead: set DefaultScheme / DefaultChallengeScheme explicitly, and name schemes on policies with AddAuthenticationSchemes where an endpoint needs a specific one.Authentication is plumbing; authorisation is where the security bugs live. A senior answer keeps the handler thin (validate the credential, build claims) and puts every decision in policies, so the rules are testable and visible in one place. The fallback policy is the single cheapest control in ASP.NET Core: it turns 'forgot an attribute' from a breach into a 401.
| Option | When it fits | Cost | When not to |
|---|---|---|---|
| One scheme (JWT or cookies) | Pure API or pure web app | Lowest complexity | When browsers and machine clients share endpoints |
| Cookie + OIDC challenge | Server-rendered web app or BFF with external login | Redirect flow, Data Protection keys to manage | Machine-to-machine APIs |
| Several schemes + policy schemes | API serving both a web front end and partners | Harder to reason about the default | If you can split into separate hosts instead |
Measure it: log authentication failures by reason (Microsoft.AspNetCore.Authentication category) and alert on a spike, which usually means a key rollover or clock problem rather than an attack.
Middleware is a component in the request pipeline: a RequestDelegate that receives the HttpContext, can do work, calls next to pass the request on, and can do more work when the response comes back. It can also short-circuit by not calling next. Use adds middleware that may call next; Run adds terminal middleware; Map branches the pipeline by path; UseWhen branches on a condition and rejoins, MapWhen branches without rejoining. Because each middleware wraps the next, order is behaviour: exception handling first, then HTTPS, static files, routing, CORS, authentication, authorisation and finally endpoints. Custom middleware can be convention-based (a class with InvokeAsync, created once as a singleton) or implement IMiddleware (resolved from DI per request). The trade-off: convention-based is the fastest default; IMiddleware is clearer when you need scoped dependencies.
All four are symptoms of a pipeline that doesn't match the documented order. I'd write the pipeline out from Program.cs and check it against exception handler → HTTPS → static files → routing → CORS → authentication → authorisation → endpoints. Auth bypass: UseAuthorization missing, before UseRouting, or the endpoint simply has no policy and there is no fallback policy. CORS: UseCors placed after authentication, so the preflight OPTIONS gets a 401 without CORS headers, or the policy isn't applied to the endpoint. Blank 500: UseExceptionHandler registered after the middleware that threw, AddProblemDetails not called, or the response had already started. Static files: files in wwwroot are public by design when UseStaticFiles runs first. I confirm each with Debug-level framework logs and lock the fix in with WebApplicationFactory tests.
The status code tells clients and infrastructure what happened before they read the body, so it must be exact.
200 OK with a body, 201 Created plus a Location header, 202 Accepted for work that finishes later, 204 No Content when there's nothing to return.400 bad input, 422 well-formed but semantically invalid, 401 not authenticated vs 403 not allowed, 404 not found vs 410 gone, 409 conflicts with current state, 412 a precondition like If-Match failed, 429 rate limited with Retry-After.500 our bug, 502 bad upstream response, 503 temporarily unavailable, 504 upstream timeout.The trade-off is precision versus consistency: pick a small, documented set and use it the same way in every service.
Last updated 23 Nov 2026.