Diagnosing authorisation that seems ignored: middleware order (UseRouting, UseAuthentication, UseAuthorization), endpoint metadata, AllowAnonymous precedence, missing default scheme, 401 vs 403 and cookie redirects, group metadata and authorisation debug logs.
Start with the pipeline and the endpoint metadata, then the logs.
UseAuthentication then UseAuthorization, after routing and before endpoints. Middleware that writes a response earlier (custom handlers, UseStaticFiles for a path, a terminal Map) bypasses authorisation.IAuthorizeData, or is there an AllowAnonymous that wins? Endpoints mapped on app instead of the group variable get none of the group's policies.Enable Microsoft.AspNetCore.Authentication and .Authorization debug logging: it tells you which scheme ran and which requirement failed.
"I'd treat it as three separate problems and check them in order: is authorisation running at all, does the endpoint carry the metadata I think it does, and is authentication producing the user I expect.
First the pipeline. Authorisation in endpoint routing is just middleware that reads the selected endpoint's metadata. If
UseAuthorizationis missing, or registered before routing has selected the endpoint, or some custom middleware writes the response before it, the[Authorize]attribute is simply never evaluated. Then the metadata: I dump the endpoint's metadata, either in a test throughEndpointDataSourceor by setting a breakpoint and looking atHttpContext.GetEndpoint().Metadata. Common surprises are an[AllowAnonymous]on a base controller or a convention, which beats every[Authorize], and Minimal API endpoints mapped onappinstead of on the group variable, so they never got the group'sRequireAuthorization.Then 401 versus 403. 401 means the challenge ran: the user isn't authenticated, as far as the policy's schemes are concerned. So if I expect a 403 but get a 401, the token is being rejected or not even read: there's no default authenticate scheme, the policy names a different scheme, or validation fails on issuer, audience or signing key. The debug logs from
Microsoft.AspNetCore.Authenticationsay exactly that, for example 'Bearer was not authenticated. Failure message: IDX10214: Audience validation failed'. With cookie authentication, the other surprise is a 302 to the login page instead of a 401; since .NET 10 the cookie handler returns 401 and 403 for endpoints it recognises as APIs, but older apps and plain endpoints still redirect. The senior line: never guess with authorisation; turn on the logs and read the endpoint metadata, because both tell you the truth in minutes."
| Symptom | Likely cause | Check |
|---|---|---|
| Anonymous caller gets 200 | UseAuthorization missing or too early; AllowAnonymous somewhere; endpoint outside the group |
Pipeline order, endpoint metadata |
| 401 with a valid-looking token | No default scheme, wrong scheme, audience/issuer/key failure | Authentication debug logs, jwt.ms |
| 401 instead of 403 | Policy specifies another scheme, or the token isn't read on that path | AuthenticationSchemes on the policy |
302 to /Account/Login from an API |
Cookie scheme challenging a non-API endpoint | Default challenge scheme, API metadata |
| 403 for everyone | Role or scope claim name mismatch | Claims on HttpContext.User, RoleClaimType |
| Group policy not applied | Endpoint mapped on app, not the group |
Endpoint metadata |
After a refactor that split Program.cs into extension methods, [six] report endpoints were mapped on app instead of the authorised /reports group and returned data anonymously for [two days]. An integration test that enumerates endpoints and asserts authorisation metadata now runs on every build and has caught [three] similar regressions since.
Checks a methodical approach to authorisation bugs: pipeline order, endpoint metadata, the difference between authentication and authorisation failures, and guard rails.
Green flags
AllowAnonymous wins and that group metadata only applies to endpoints mapped on the groupRed flags
AllowAnonymous or removes [Authorize] to make it workapp.UseExceptionHandler()
app.UseHttpsRedirection()
app.UseStaticFiles() // serves files without auth unless you configure otherwise
app.UseRouting() // optional in .NET 6+, added implicitly at the start if omitted
app.UseCors() // must be between routing and auth for endpoint CORS
app.UseAuthentication() // sets HttpContext.User from the default authenticate scheme
app.UseAuthorization() // evaluates the selected endpoint's metadata
app.UseRateLimiter()
app.MapControllers() / MapGroup(...)
If custom middleware calls UseRouting explicitly after UseAuthorization, authorisation runs with no endpoint selected, sees no metadata and lets everything through (or applies only the fallback policy).
For controllers: global filters and conventions, controller attributes, action attributes. For Minimal APIs: group conventions, then endpoint conventions. Everything is a list; the authorisation middleware collects all IAuthorizeData and policies and checks for IAllowAnonymous. Any IAllowAnonymous short-circuits authorisation entirely (since .NET 6 it is checked as endpoint metadata regardless of where it was added).
GET /reports/sales
metadata: [HttpMethodMetadata, AuthorizeAttribute("Reports"), AllowAnonymousAttribute] -> anonymous wins
policy fails
user authenticated for the policy's schemes? no -> ChallengeAsync(schemes) -> 401 / 302 login
yes -> ForbidAsync(schemes) -> 403 / 302 access denied
"Authenticated" is judged for the policy's schemes. If the policy says AuthenticationSchemes = "ApiKey" and the caller sent a JWT, the user is anonymous for that policy and gets a 401.
AddAuthentication() with no default and more than one scheme registered means UseAuthentication doesn't know which handler to run. Since .NET 7 a single registered scheme becomes the default automatically; add a second (for example cookies for Identity plus JWT) and the default disappears unless you set it. Symptom: HttpContext.User is always anonymous, so every protected endpoint returns 401.
The cookie handler's challenge redirects to LoginPath. In .NET 10 it returns 401 or 403 instead for endpoints with IApiEndpointMetadata (controllers with [ApiController], Minimal API endpoints that read or write JSON). Endpoints without that metadata still redirect; you can override with options.Events.OnRedirectToLogin.
"Logging": { "LogLevel": {
"Microsoft.AspNetCore.Authentication": "Debug",
"Microsoft.AspNetCore.Authorization": "Debug" } }
Typical lines: AuthenticationScheme: Bearer was challenged., Authorization failed. These requirements were not met: RolesAuthorizationRequirement:User.IsInRole must be true for one of the following roles: (Admin). They tell you whether you have an authentication problem or an authorisation problem.
UseAuthorization above UseRouting in a test app and observe protected endpoints returning 200.[AllowAnonymous] to a base controller and watch the derived controller's [Authorize] stop working.Broken: authorisation evaluated with no endpoint selected, and an endpoint mapped outside its group.
// Program.cs (broken)
var app = builder.Build();
app.UseAuthentication();
app.UseAuthorization(); // runs before routing: no endpoint, no metadata
app.UseRouting(); // explicit routing after authorisation
var reports = app.MapGroup("/reports").RequireAuthorization("Reports");
reports.MapGet("/sales", GetSales);
app.MapGet("/reports/payroll", GetPayroll); // mapped on app: no group policy at all
Fixed: correct order, explicit schemes, and a test that fails the build when an endpoint has no authorisation metadata.
// Program.cs (.NET 10)
builder.Services.AddAuthentication(options =>
{
options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme; // two schemes: set the default
})
.AddJwtBearer()
.AddCookie("Admin");
builder.Services.AddAuthorizationBuilder()
.SetFallbackPolicy(new AuthorizationPolicyBuilder().RequireAuthenticatedUser().Build())
.AddPolicy("Reports", p => p.RequireRole("Finance"));
var app = builder.Build();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
var reports = app.MapGroup("/reports").RequireAuthorization("Reports");
reports.MapGet("/sales", GetSales);
reports.MapGet("/payroll", GetPayroll); // on the group variable
app.MapGet("/healthz", () => Results.Ok()).AllowAnonymous();
// EndpointAuthorizationTests.cs (xUnit + WebApplicationFactory)
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc.Testing;
using Microsoft.AspNetCore.Routing;
using Microsoft.Extensions.DependencyInjection;
using Xunit;
public sealed class EndpointAuthorizationTests(WebApplicationFactory<Program> factory)
: IClassFixture<WebApplicationFactory<Program>>
{
private static readonly string[] PublicRoutes = ["/healthz"];
[Fact]
public void Every_endpoint_declares_authorisation_or_is_explicitly_public()
{
var endpoints = factory.Services.GetRequiredService<EndpointDataSource>().Endpoints
.OfType<RouteEndpoint>();
var unprotected = endpoints
.Where(e => e.Metadata.GetMetadata<IAuthorizeData>() is null
&& e.Metadata.GetMetadata<IAllowAnonymous>() is null)
.Select(e => e.RoutePattern.RawText)
.ToList();
var anonymous = endpoints
.Where(e => e.Metadata.GetMetadata<IAllowAnonymous>() is not null)
.Select(e => e.RoutePattern.RawText)
.Where(r => !PublicRoutes.Contains(r))
.ToList();
Assert.Empty(unprotected); // relies on the fallback policy otherwise; be explicit
Assert.Empty(anonymous); // AllowAnonymous only on the approved list
}
}
UseRouting after UseAuthorization, or putting custom middleware that writes responses before it. Why it is wrong: authorisation runs with no endpoint metadata, so nothing is enforced. Instead: routing, authentication, authorisation, endpoints, in that order.[AllowAnonymous] on a base controller, convention or group. Why it is wrong: it overrides every [Authorize] below it. Instead: keep AllowAnonymous on individual public endpoints and assert the list in a test.app when they belong to an authorised group. Why it is wrong: the group's conventions never apply. Instead: map on the group variable and test endpoint metadata.UseAuthentication doesn't know which handler to run, so every request is anonymous. Instead: set DefaultScheme or name schemes on policies.[Authorize] conventions to apply to Minimal API endpoints. Why it is wrong: MVC conventions only apply to controllers. Instead: RequireAuthorization on groups, or the fallback policy.AllowAnonymous "temporarily". Why it is wrong: temporary exceptions ship. Instead: find the claim or policy mismatch in the logs.These bugs are almost never subtle once you look at the right data, and they are almost always caused by refactoring rather than by the original design. So I invest in guard rails: a fallback policy, an endpoint-metadata test, and debug logging that can be switched on per environment without a redeploy.
| Guard rail | Catches | Cost | Limitation |
|---|---|---|---|
| Fallback policy | Endpoints with no metadata | Explicit AllowAnonymous on public routes |
Doesn't catch a wrong policy |
| Endpoint-metadata test | Missing or unexpected anonymous endpoints | One test | Doesn't prove the policy logic |
| Cross-user and anonymous integration tests | Wrong policy, missing resource checks | Test data per role | Needs maintenance |
| Authorisation debug logs | Exact failed requirement or scheme | Log volume when on | Turn on temporarily |
Measure it: chart 401 and 403 rates per endpoint in Application Insights; a step change right after a deployment is the fastest signal that the pipeline or claim mapping changed.
Middleware is a component in the request pipeline: a RequestDelegate that receives the HttpContext, can do work, calls next to pass the request on, and can do more work when the response comes back. It can also short-circuit by not calling next. Use adds middleware that may call next; Run adds terminal middleware; Map branches the pipeline by path; UseWhen branches on a condition and rejoins, MapWhen branches without rejoining. Because each middleware wraps the next, order is behaviour: exception handling first, then HTTPS, static files, routing, CORS, authentication, authorisation and finally endpoints. Custom middleware can be convention-based (a class with InvokeAsync, created once as a singleton) or implement IMiddleware (resolved from DI per request). The trade-off: convention-based is the fastest default; IMiddleware is clearer when you need scoped dependencies.
Start with evidence, not guesses. A JwtBearer 401 includes a WWW-Authenticate header with an error_description, and the Microsoft.AspNetCore.Authentication logs at Debug level show an IDX error code.
Authorization header never arrived (stripped by the proxy, or dropped on an HTTP-to-HTTPS redirect).The trade-off: decoding a token at jwt.ms is fast, but only server logs tell you which check failed.
Policy-based authorisation separates what an endpoint needs from how it is checked. A policy is a named set of requirements; each requirement is plain data (IAuthorizationRequirement) and one or more handlers decide whether it is met. All requirements must pass; for a single requirement, any handler succeeding is enough unless one explicitly fails. Claims-based checks (RequireClaim("scope", "orders.read")) are just built-in requirements.
[Authorize(Policy = "...")] or RequireAuthorization("...") on Minimal API endpoints and MapGroup.[Authorize] uses; FallbackPolicy applies to endpoints with no authorisation metadata.The trade-off: a fallback policy makes the app secure by default, at the cost of explicitly marking public endpoints with AllowAnonymous.
How to tell it (STAR)
**S:** After we split our [HR] API's `Program.cs` into feature files, [six] payroll report endpoints were mapped outside their authorised group and returned salary data to anonymous callers. **T:** I led the fix and the follow-up. **A:** I confirmed the gap by dumping endpoint metadata, hot-fixed the mapping, set a fallback policy so unprotected endpoints were closed by default, and worked with [the privacy officer] on the access logs to assess the exposure. Then I added a CI test that fails if any endpoint lacks authorisation metadata or isn't on the approved anonymous list. **R:** The fix was live within [two hours], logs showed [no access from outside the corporate network], and the test has blocked [three] similar mistakes since.
Last updated 23 Nov 2026.