⚙️ C# / .NET Intermediate

What is middleware authentication vs authorization in ASP.NET Core?

Answer

In ASP.NET Core's pipeline, authentication and authorization are separate middleware. Authentication middleware (app.UseAuthentication()): reads the request (cookies, JWT header, API key) and populates HttpContext.User with the identity if valid — answering "who is this?" Configured with schemes: builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer(...);. Authorization middleware (app.UseAuthorization() — must come after authentication): checks if the authenticated user has permission to perform the requested action. Uses policies, roles, and claims. [Authorize(Policy = "AdminOnly")] on controllers/endpoints. Policies: builder.Services.AddAuthorization(opts => opts.AddPolicy("AdminOnly", p => p.RequireRole("Admin")));. Order matters: UseRouting → UseAuthentication → UseAuthorization → MapControllers. Authentication must always run before authorization so the user identity is established first.