ASP.NET Core › Authentication

What is the purpose of the authentication middleware's position in the pipeline, and why must UseAuthentication come before UseAuthorization?

Intermediate

Answer

UseAuthentication establishes the request's identity (populating HttpContext.User) by running the configured authentication handler(s), which UseAuthorization then depends on to evaluate policy and role requirements -- registering them in the wrong order means authorization checks would run against an unauthenticated (empty) principal, incorrectly rejecting legitimately authenticated users.
app.UseRouting();
app.UseAuthentication();  // MUST come first: establishes HttpContext.User
app.UseAuthorization();   // depends on User already being populated
app.MapControllers();
Real-world example A team debugging why all authenticated requests were incorrectly receiving 401 responses discovers UseAuthorization was accidentally registered before UseAuthentication, meaning no identity had been established yet when authorization checks ran.

Common follow-ups: What HttpContext state does UseAuthentication actually populate?;Does this ordering requirement apply the same way to minimal APIs as MVC controllers?