ASP.NET Core Middleware Order: Why Authentication Must Precede Authorization
The author recounts a production incident caused by placing UseAuthorization before UseAuthentication in the ASP.NET Core pipeline, explaining how middleware order determines request processing flow and why authentication must run before authorization to populate HttpContext.User for policy checks.
Reading font

The author describes a real production issue caused by misordering two critical middleware components in an ASP.NET Core application:
app.UseAuthorization();
app.UseAuthentication();After deployment, every endpoint requiring authorization failed its authorization check. The root cause: HttpContext.User was still null when the authorization middleware ran because the authentication middleware — which populates the user principal from the request — had not yet executed.
Correct Middleware Sequence
A typical, safe ordering for an ASP.NET Core pipeline is:
app.UseExceptionHandler("/Error"); // 1. Exception handling (earliest)
app.UseHttpsRedirection(); // 2. HTTPS redirection
app.UseStaticFiles(); // 3. Static files (can short‑circuit)
app.UseRouting(); // 4. Routing
app.UseAuthentication(); // 5. Authentication (first)
app.UseAuthorization(); // 6. Authorization (after auth)
app.MapControllers(); // 7. EndpointsWhy Order Matters
Exception handling first : It must wrap all subsequent middleware so it can catch any exception thrown downstream.
Static files before authentication : Otherwise every request for a CSS, JS, or image file would trigger the authentication pipeline, wasting CPU and adding latency.
Authentication before authorization : Authorization decisions depend on knowing who the caller is. The authentication middleware builds the ClaimsPrincipal and assigns it to HttpContext.User; without that, authorization policies have no identity to evaluate.
The article emphasizes that middleware order determines behavior — a foundational principle when composing the request pipeline. When adding custom middleware, developers must understand which upstream components their middleware depends on and which downstream components depend on its output.
About this article
For attribution, corrections or content rights, contact