📁 Sangam Dhakal - Portfolio v2.0 - Netscape Navigator 4.0
_
□
×

📚 Interview question

Your ASP.NET Core API seems to ignore [Authorize]: some endpoints return data to anonymous callers, others return 401 when you expect 403, and a policy on a Minimal API route group doesn't seem to apply. How do you diagnose and fix it?

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.

Mid-Level Debugging Intermediate aspnet-core authorization debugging middleware minimal-apis security

🎯 Key points

  • Check order: UseRouting (if explicit), UseAuthentication, UseAuthorization, then endpoints; custom middleware that short-circuits before UseAuthorization bypasses it
  • Inspect the endpoint's metadata (EndpointDataSource or a debug endpoint): IAuthorizeData, IAllowAnonymous, policies
  • AllowAnonymous anywhere (controller, group, convention) beats every [Authorize]
  • 401 = not authenticated (challenge); 403 = authenticated but denied (forbid)
  • 401 when you expect 403 usually means the token wasn't accepted: no default scheme (one scheme is the default automatically since .NET 7, two or more need DefaultScheme / DefaultAuthenticateScheme / DefaultChallengeScheme), wrong scheme on the policy, or validation failure
  • Cookie auth redirects to the login page (302) for non-API endpoints; in .NET 10 it returns 401/403 for endpoints with IApiEndpointMetadata
  • Group metadata only applies to endpoints mapped through that group object; MVC filters and conventions don't apply to Minimal APIs
  • Turn on Microsoft.AspNetCore.Authentication and .Authorization debug logs to see the exact reason

⏱ 30-second answer

Start with the pipeline and the endpoint metadata, then the logs.

  • Order: 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.
  • Metadata: does the endpoint actually carry IAuthorizeData, or is there an AllowAnonymous that wins? Endpoints mapped on app instead of the group variable get none of the group's policies.
  • 401 vs 403: 401 means authentication failed or never ran (no default scheme, wrong scheme, issuer or audience mismatch); 403 means a policy denied an authenticated user.

Enable Microsoft.AspNetCore.Authentication and .Authorization debug logging: it tells you which scheme ran and which requirement failed.

🗣 Full answer (senior)

How I would answer this in an interview

"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 UseAuthorization is 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 through EndpointDataSource or by setting a breakpoint and looking at HttpContext.GetEndpoint().Metadata. Common surprises are an [AllowAnonymous] on a base controller or a convention, which beats every [Authorize], and Minimal API endpoints mapped on app instead of on the group variable, so they never got the group's RequireAuthorization.

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.Authentication say 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 to likely cause

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

Production example

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.

🔍 What the interviewer is checking

Checks a methodical approach to authorisation bugs: pipeline order, endpoint metadata, the difference between authentication and authorisation failures, and guard rails.

Green flags

  • Checks middleware order and endpoint metadata first
  • Explains 401 vs 403 in terms of challenge and forbid
  • Knows AllowAnonymous wins and that group metadata only applies to endpoints mapped on the group
  • Turns on authentication and authorisation debug logs
  • Adds a test so it can't regress

Red flags

  • Adds AllowAnonymous or removes [Authorize] to make it work
  • Changes token settings at random without reading logs
  • Doesn't know a missing default scheme makes every user anonymous

📚 Learn in depth

1. The pipeline that has to be right

app.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).

2. How metadata is combined

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

3. Challenge vs forbid

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.

4. The default scheme

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.

5. Cookie redirects and APIs

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.

6. The logs

"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.

Try it yourself

  1. Move UseAuthorization above UseRouting in a test app and observe protected endpoints returning 200.
  2. Add [AllowAnonymous] to a base controller and watch the derived controller's [Authorize] stop working.
  3. Register cookies and JWT without a default scheme and read the authentication logs.
  4. Write the endpoint-enumeration test from the code example and break it on purpose.

💻 Code

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
    }
}

⚠ Common mistakes

  • Mistake: Calling 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.
  • Mistake: [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.
  • Mistake: Mapping endpoints on 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.
  • Mistake: Registering two authentication schemes and no default. Why it is wrong: UseAuthentication doesn't know which handler to run, so every request is anonymous. Instead: set DefaultScheme or name schemes on policies.
  • Mistake: Treating 401 and 403 as the same. Why it is wrong: 401 points at authentication (token, scheme), 403 at authorisation (policy, claims); debugging the wrong one wastes hours. Instead: read the status and the authentication logs first.
  • Mistake: Expecting MVC filters or [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.
  • Mistake: Fixing a 403 by adding AllowAnonymous "temporarily". Why it is wrong: temporary exceptions ship. Instead: find the claim or policy mismatch in the logs.

🏛 Senior insight: trade-offs

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.

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions middleware order Why: Checks they understand middleware ordering and short-circuiting in general
    How to answer

    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.

  2. When: Candidate says the 401 comes from token validation Why: Checks they can diagnose the token side when 401s come from validation failures
    How to answer

    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.

    • IDX10214 / IDX10205: audience or issuer mismatch, often a different tenant, App ID URI or v1 vs v2 token.
    • IDX10223: expired, or clock skew on the host.
    • IDX10500/10503: signing key not found or signature invalid, a hard-coded key after rollover.
    • IDX20803: the API can't reach the metadata/JWKS endpoint through the egress firewall or proxy.
    • No error at all: the 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.

  3. When: Candidate suggests making endpoints secure by default Why: Checks they know default versus fallback policy as a guard rail
    How to answer

    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.

    • Apply with [Authorize(Policy = "...")] or RequireAuthorization("...") on Minimal API endpoints and MapGroup.
    • DefaultPolicy is what plain [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.

🛠 Real-world problems: how you handle them

Payroll report endpoints served data anonymously after a Program.cs refactor
Situation
An internal [HR] API on Azure App Service (Australia East) was refactored from one `Program.cs` into feature extension methods. [Six] report endpoints containing salary data were mapped on `app` instead of the authorised `/reports` group.
Signals
A [security engineer's] routine OWASP ZAP baseline scan flagged 200 responses without credentials on `/reports/payroll`; Application Insights showed requests to those endpoints with no authenticated user id for [two days].
Investigation
Reproduced with curl without a token; dumped endpoint metadata in a test and saw no `IAuthorizeData` on the six endpoints; confirmed via `git blame` that the refactor mapped them on `app`; checked request logs for anonymous calls from outside the corporate network to assess exposure, with [the privacy officer] reviewing whether it was an eligible data breach under the NDB scheme.
Resolution
Immediate: hot-fix moving the endpoints onto the group and setting a fallback policy requiring an authenticated user. Then added the endpoint-metadata test, cross-role integration tests for report endpoints, and an approved list of anonymous routes.
Prevention
Endpoint-metadata test in CI; fallback policy as a standard in the service template; ZAP baseline scan in the pipeline; alert on anonymous requests to `/reports/*`.

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.

↩ Usually asked after

More in Authorization

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me