ASP.NET Core Interview Question #97
Where should authentication and authorization middleware be placed?
Middleware & Request Pipeline Mid-Level Intermediate
Quick Interview Answer
Authentication should normally run before authorization. Authentication establishes the current user identity, while authorization evaluates whether that user is allowed to access the selected resource.
Detailed Explanation
Authentication should normally run before authorization. Authentication establishes the current user identity, while authorization evaluates whether that user is allowed to access the selected resource.
In a conventional endpoint-routing pipeline, UseAuthentication() and UseAuthorization() are placed after routing has selected endpoint metadata and before mapped endpoints execute.
The exact pipeline can vary by application style, but reversing these two middleware components is a common configuration error.
Code Example
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.MapControllers();