skip to content

In an ASP.NET Core 10 Program.cs, what order do the docs prescribe for built-in middleware, and what breaks if UseAuthorization runs before UseAuthentication?

level: middleimportance: must knowfreq 74%

answer

  1. errors first, endpoints last
  2. HTTPS redirection, then static files
  3. UseRouting before CORS and auth
  4. UseCors, UseAuthentication, UseAuthorization
  5. UseAntiforgery after authorization

basics

~10 s

Exception handler and HSTS, HTTPS redirection, static files, routing, CORS, authentication, authorization, antiforgery, then endpoints. With authorization first, a default [Authorize] policy sees an anonymous user, so valid tokens get 401.

solid answer

~40 s

The documented order is: `UseExceptionHandler` and `UseHsts` (outside Development), `UseHttpsRedirection`, static files, `UseCookiePolicy`, `UseRouting`, `UseRateLimiter` (after routing when endpoint policies are used), `UseRequestLocalization`, `UseCors`, `UseAuthentication`, `UseAuthorization`, `UseAntiforgery`, `UseSession`, response compression and caching, then the endpoint maps. Swap authentication and authorization and the authorization middleware evaluates `HttpContext.User` before any scheme has populated it: a policy that names no scheme sees an anonymous principal and challenges, so a valid JWT still gets 401. Put `UseAuthorization` before `UseRouting` and it sees no endpoint, so the endpoint middleware throws an `InvalidOperationException` for any endpoint with authorization metadata. `UseCors` also belongs before `UseResponseCaching`, so cached responses carry CORS headers.

code

csharp · 23 lines
csharp
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddProblemDetails();
builder.Services.AddCors(o => o.AddPolicy("kiosk",
    p => p.WithOrigins("https://kiosk.museum.example")));
builder.Services.AddAuthentication().AddJwtBearer();
builder.Services.AddAuthorization();

var app = builder.Build();

if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler();
    app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();          // wwwroot/audio/*.mp3, answered early
app.UseRouting();
app.UseCors("kiosk");
app.UseAuthentication();       // fills HttpContext.User
app.UseAuthorization();        // reads the user and the selected endpoint

app.MapGet("/tours/{id:int}", (int id) => Results.Ok(id)).RequireAuthorization();
app.Run();

go deeper

for a junior

Recite the order from exception handling to endpoints and remember that authentication comes before authorization.

for a middle

Explain what each step reads from an earlier one, and predict the status code when authentication, authorization or CORS moves.

for a senior

Diagnose misordering from symptoms such as valid tokens getting 401, CORS errors on rejected calls, or endpoint-level limits not applied.

for a principal

Set a team convention for where new middleware may be inserted, and review pipeline changes for what each component reads and short-circuits.

## Why order is a correctness issue ASP.NET Core runs middleware in the order the `Use...` calls appear in `Program.cs` on the way in, and in reverse on the way out. Most built-in middleware reads something an earlier component prepared: authorization reads the user that authentication set and the endpoint that routing selected; CORS needs the selected endpoint to apply endpoint-level policies; antiforgery needs to know whether the user was authenticated. Move one call and the component still runs, only on the wrong inputs, which is why misordering usually shows up as a wrong status code, not a startup error. ## The documented order The ASP.NET Core docs give this order for an app that uses all of them: 1. `UseExceptionHandler` and `UseHsts` outside Development; the developer exception page in Development. 2. `UseHttpsRedirection`. 3. Static files (`UseStaticFiles`), which can answer and short-circuit early. 4. `UseCookiePolicy`. 5. `UseRouting`, which selects the endpoint. 6. `UseRateLimiter` (after routing when policies come from `[EnableRateLimiting]` or `RequireRateLimiting`; a global-only limiter may go before) and `UseRequestLocalization` (before anything that reads the culture). 7. `UseCors`. 8. `UseAuthentication`. 9. `UseAuthorization`. 10. `UseAntiforgery`, which must come after authentication and authorization. 11. `UseSession`, then response compression and `UseResponseCaching` where used (`UseCors` must precede `UseResponseCaching` so cached responses still get CORS headers). 12. The endpoint maps: `MapControllers`, `MapRazorPages`, `MapGet`, `MapStaticAssets` and friends. ## Concrete failures when a call moves | Misplacement | What happens | |---|---| | `UseAuthorization` before `UseAuthentication` | the policy is evaluated against an empty `ClaimsPrincipal`; a valid bearer token still gets 401 | | `UseAuthorization` before an explicit `UseRouting` | authorization sees no endpoint; the endpoint middleware throws `InvalidOperationException` because the endpoint has authorization metadata but no middleware handled it | | `UseCors` after authentication and authorization | 401 and 403 responses are written before CORS runs, so they carry no `Access-Control-Allow-Origin` and the browser reports a CORS error | | `UseRateLimiter` before `UseRouting` with endpoint policies | the limiter cannot see the endpoint's policy metadata, so those endpoint limits are not applied | | `UseResponseCaching` before `UseCors` | responses replayed from the cache miss the CORS headers | The first row has one nuance. `AuthorizationMiddleware` asks the policy evaluator to authenticate. If the policy lists its own `AuthenticationSchemes` (for example `[Authorize(AuthenticationSchemes = "Bearer")]`), the evaluator authenticates those schemes itself and the request succeeds anyway. The default policy names no scheme, so it relies on `HttpContext.User`, which only the authentication middleware fills. ## The museum audio-guide API A museum's audio-guide API serves MP3 clips from `wwwroot/audio`, answers a kiosk web app on another origin, and protects tour data with JWT bearer tokens. Its `Program.cs` follows the order exactly: ```csharp if (!app.Environment.IsDevelopment()) { app.UseExceptionHandler(); app.UseHsts(); } app.UseHttpsRedirection(); app.UseStaticFiles(); app.UseRouting(); app.UseCors("kiosk"); app.UseAuthentication(); app.UseAuthorization(); app.MapGet("/tours/{id:int}", (int id) => Results.Ok(id)).RequireAuthorization(); ``` The audio clips are answered by the static file middleware before routing or authentication run, which is cheap, and also means they are public. Outside Development, errors anywhere below are caught by the exception handler because it is the outermost layer. ## What the templates write The ASP.NET Core 10 `webapi` template with controllers writes a short pipeline: `MapOpenApi()` in Development, `UseHttpsRedirection()`, `UseAuthorization()`, `MapControllers()`. It never calls `UseRouting` or `UseAuthentication`. That works because `WebApplication` adds routing at the start of the pipeline and, when an authentication option registered `AddAuthentication`, inserts `UseAuthentication` ahead of your code. The moment you add a call that must sit between them, such as `UseCors` or a custom middleware that reads `HttpContext.User`, write the full sequence yourself so the order on the page is the order that runs. ## How to reason about a new middleware - Ask what it **reads**: the endpoint (needs routing first), the user (needs authentication first), the culture (needs localization first). - Ask what it **short-circuits**: static files and CORS preflight answers end the request early; put them where skipping the rest is safe. - Ask what it must **wrap**: exception handling and response compression must enclose the components whose output they handle. - Call `UseAuthentication` and `UseAuthorization` yourself whenever you also call `UseCors` or `UseRouting`; leaving them to `WebApplication` places them ahead of your own middleware.

  • What happens if UseAuthorization is placed before an explicit UseRouting call?
    Authorization runs before an endpoint is selected, so it cannot see the endpoint's `[Authorize]` or `RequireAuthorization` metadata. When the endpoint middleware later finds that metadata unhandled, it throws an `InvalidOperationException` telling you to call `UseAuthorization` between `UseRouting` and `UseEndpoints` (unless `RouteOptions.SuppressCheckForUnhandledSecurityMetadata` is set).
  • Where does UseRateLimiter go?
    After `UseRouting` when endpoints opt into policies with `[EnableRateLimiting]` or `RequireRateLimiting`, because the limiter reads that policy from the selected endpoint. If the app only uses a global limiter, it may run before routing.
  • Why do the docs put UseCors before UseResponseCaching?
    So the CORS middleware runs for every request, including the ones the response caching middleware answers from its cache. In the other order a cached response is replayed without the CORS headers the browser needs.

  • Authentication middleware rejects anonymous requests by itself, so its position barely matters.
  • UseAuthorization can sit anywhere because it triggers authentication when it needs a user.
  • UseCors should follow UseAuthorization so only authenticated callers get CORS headers.
  • UseRateLimiter must always come before UseRouting.
  • A wrong middleware order is caught at startup with a clear exception.