UseAuthentication adds authentication middleware at a chosen point in the ASP.NET Core request pipeline. The middleware establishes the current principal when a user logs in and can load it from an authentication cookie on later requests. section 23.7
Place authentication where later middleware can use the authenticated request:
- Call UseAuthentication before middleware that requires an authenticated user, especially UseAuthorization. section 23.7
- When controlling the pipeline explicitly, keep UseRouting, UseAuthentication, UseAuthorization, and UseEndpoints in that overall order. section 24.2
- WebApplication adds AuthenticationMiddleware automatically, but UseAuthentication lets you ensure its position explicitly. section 23.7
Explicit middleware order
A pipeline that makes the dependency visible can be written as: app.UseRouting(); app.UseAuthentication(); app.UseAuthorization(); app.UseEndpoints(...). Authentication populates HttpContext.User before authorization evaluates whether the selected endpoint may execute. section 24.2 section 23.7
Figure 24.2 Authorization occurs after an endpoint has been selected and after the request is authenticated, but before the action method or Razor Page endpoint is executed.
The pipeline figure clarifies that authentication happens after endpoint selection and before authorization and endpoint execution. section 24.2
