HTTP 401 Unauthorized or 403 Forbidden returned unexpectedly despite valid credentials and authorization configuration
ID: dotnet/aspnet-middleware-order
Version Compatibility
| Version | Status | Introduced | Deprecated | Notes |
|---|---|---|---|---|
| 8 | active | — | — | — |
Root Cause
ASP.NET Core middleware order errors cause unexpected 401/403 responses even when authentication is correctly configured. The middleware pipeline is order-dependent: UseAuthentication must come before UseAuthorization, and both must come after UseRouting but before MapControllers. Fix by correcting the middleware registration order in Program.cs.
genericWorkarounds
-
92% success Ensure correct middleware order in Program.cs
The correct order is: app.UseRouting(); app.UseCors(); app.UseAuthentication(); app.UseAuthorization(); app.MapControllers(); Authentication MUST come before Authorization. Both MUST come after UseRouting. CORS middleware must be before Authentication if CORS preflight is needed
-
88% success Verify authentication services are properly registered in DI
Ensure Program.cs includes: builder.Services.AddAuthentication(defaultScheme).AddJwtBearer(options => { ... }); and builder.Services.AddAuthorization(); Check that the default authentication scheme matches the scheme used in [Authorize] attributes or policy definitions
Dead Ends
Common approaches that don't work:
-
Adding [AllowAnonymous] to controllers to work around 401/403 errors
85% fail
Bypasses security entirely instead of fixing the middleware order; leaves endpoints unprotected and masks the configuration bug that will affect other secured endpoints
-
Registering authentication services multiple times with different schemes
70% fail
Adding duplicate authentication registrations creates ambiguity in scheme resolution; the default scheme may not be the one intended, and the middleware order issue remains regardless of how many schemes are registered