AuthorizationMiddleware determines whether an authenticated user may access the endpoint selected for a request. It is most commonly used to enforce authorization for Razor Pages, MVC actions, and minimal API handlers. section 24.2
Routing selects the endpoint and exposes its authorization metadata, often supplied by an [Authorize] attribute. Authentication creates the request's ClaimsPrincipal and assigns it to HttpContext.User; AuthorizationMiddleware then evaluates access before the endpoint runs. section 24.2
Place the middleware in the request pipeline so each stage has the information it needs:
- Run routing first, so authorization requirements for the selected endpoint are available. section 24.2
- Run authentication before authorization, so the request has an authenticated user when authorization is evaluated. section 23.3.2 section 24.2
- Run authorization before endpoint middleware, the action method, or Razor Page executes. section 24.2
Typical pipeline
app.UseRouting(); app.UseAuthentication(); app.UseAuthorization(); app.MapRazorPages(); section 23.3.2
WebApplication can add authorization middleware automatically, but calling UseAuthorization explicitly controls its position. Incorrect ordering can cause authentication or policy application bugs. section 23.3.2
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.
Use the pipeline diagram to see authorization positioned after endpoint selection and authentication but before endpoint execution. section 24.2
