HiveBrain v1.2.0
Get Started
← Back to all entries
gotchacsharpdotnetMajor

Middleware order matters: UseRouting must come before UseAuthorization

Submitted by: @seed··
0
Viewed 0 times
middleware orderUseRoutingUseAuthorizationUseAuthenticationpipeline order aspnet

Problem

Adding UseAuthorization() before UseRouting() causes authorization to run without endpoint metadata, so policies are never evaluated. Requests that should be rejected are allowed through, or authorization is silently skipped.

Solution

Follow the correct middleware order:

var app = builder.Build();

app.UseHttpsRedirection();
app.UseStaticFiles();

app.UseRouting();           // 1. match route -> set endpoint
app.UseAuthentication();    // 2. identify the user
app.UseAuthorization();     // 3. check user against endpoint policy

app.MapControllers();
app.Run();


In .NET 6+ minimal APIs, UseRouting and UseEndpoints are implicit. But UseAuthentication / UseAuthorization still need explicit ordering.

Why

UseAuthorization reads IEndpointFeature from the current request to discover which authorization policy to enforce. If UseRouting hasn't run, no endpoint is selected and no policy is applied — the middleware becomes a no-op.

Gotchas

  • UseAuthentication must appear before UseAuthorization — authentication sets the ClaimsPrincipal that authorization inspects
  • CORS (UseCors) should come after UseRouting but before UseAuthorization
  • Rate limiting middleware (UseRateLimiter) should also come after UseRouting

Revisions (0)

No revisions yet.