When an ASP.NET Core authorization policy fails, how does the framework choose between a 401 challenge and a 403 forbid, and what shapes each response?
answer
- did authentication succeed?
- PolicyAuthorizationResult.Challenge vs Forbid
- ChallengeAsync / ForbidAsync on the scheme
- cookie redirects, JwtBearer status codes
- IAuthorizationMiddlewareResultHandler
basics
~20 sThe authorization middleware forbids when the user authenticated but failed the policy, and challenges when nobody authenticated. The authentication scheme then writes the response: JwtBearer sends 401 or 403, while the cookie handler redirects browsers to LoginPath or AccessDeniedPath.
solid answer
~40 sAfter a policy fails, `PolicyEvaluator.AuthorizeAsync` checks the authentication result: if it **succeeded**, the outcome is **Forbid**; if not, it is **Challenge**. The default `IAuthorizationMiddlewareResultHandler` then calls `HttpContext.ForbidAsync()` or `ChallengeAsync()`, once per scheme listed on the policy, or else on the default forbid or challenge scheme. The **scheme decides the response**: JwtBearer returns `401` with a `WWW-Authenticate: Bearer` header, or `403`. The cookie handler redirects to `LoginPath` or `AccessDeniedPath`, but answers `401`/`403` for AJAX requests and, since ASP.NET Core 10, for endpoints marked as APIs. With no scheme registered at all, `ChallengeAsync` throws `InvalidOperationException`. Inside a handler you choose yourself: return `Forbid()` when the user is signed in, and `Challenge()` when not.
code
http · 10 linesGET /api/contracts/42 HTTP/1.1
Authorization: Bearer <expired token>
HTTP/1.1 401 Unauthorized
WWW-Authenticate: Bearer error="invalid_token", error_description="The token expired at '10/06/2026 09:00:00'"
GET /api/contracts/42 HTTP/1.1
Authorization: Bearer <valid token, no Manager role>
HTTP/1.1 403 Forbiddengo deeper
Recall that 401 means not authenticated and 403 means authenticated but not allowed, and that ASP.NET Core calls these a challenge and a forbid.
Explain the middleware's rule (forbid if authentication succeeded, else challenge) and how JwtBearer and cookie schemes each render the two outcomes.
Diagnose wrong codes in production: redirects reaching API clients, Unauthorized() bypassing the scheme, a missing default scheme, and when a 404 should hide a forbid.
Set a consistent contract for clients across services: which code means refresh, which means stop, and whether forbidden resources reveal their existence.
## Two different failures HTTP gives authorization failures two status codes, and ASP.NET Core maps them onto two operations of the authentication system: - **Challenge**: "I don't know who you are; authenticate." It usually ends in `401 Unauthorized` or a redirect to a sign-in page. - **Forbid**: "I know who you are, and you may not do this." It usually ends in `403 Forbidden` or a redirect to an access-denied page. The authorization middleware does not write either response itself. It decides **which** operation applies and asks the authentication scheme to carry it out. ## How the middleware decides For the selected endpoint, the authorization middleware combines the metadata into a policy and then: 1. Calls `IPolicyEvaluator.AuthenticateAsync`. If the policy names `AuthenticationSchemes`, each one is authenticated and the principals are merged; otherwise the result from the authentication middleware (or the current `HttpContext.User`) is used. 2. Calls `IPolicyEvaluator.AuthorizeAsync`, which runs `IAuthorizationService` with the policy. 3. On failure, returns `PolicyAuthorizationResult.Forbid(...)` when **authentication succeeded**, and `PolicyAuthorizationResult.Challenge()` otherwise. 4. Passes the result to `IAuthorizationMiddlewareResultHandler`. The default implementation calls `ChallengeAsync(scheme)` or `ForbidAsync(scheme)` for every scheme on the policy, or the parameterless versions, which use the default challenge or forbid scheme. So the decision is **only** "did authentication succeed?". A user whose token has expired gets a challenge, while a signed-in user without the `Manager` role gets a forbid. ## What each scheme writes | Scheme | Challenge | Forbid | |---|---|---| | JwtBearer | `401` with `WWW-Authenticate: Bearer` (plus `error` details when the token was rejected) | `403` | | Cookie, browser request | `302` to `LoginPath?ReturnUrl=...` | `302` to `AccessDeniedPath?ReturnUrl=...` | | Cookie, AJAX request or API endpoint in .NET 10 | `401` | `403` | | Base `AuthenticationHandler` defaults | `401` | `403` | The cookie row changed in **ASP.NET Core 10**: the cookie handler no longer redirects for endpoints the framework marks as API endpoints, such as `[ApiController]` controllers and Minimal APIs that return JSON, and answers `401` or `403` instead. Before 10 an API caller holding an expired cookie received a `302` to an HTML login page, which a JavaScript client usually followed and then failed to parse. If **no authentication scheme** is registered, or none is the default, a failed `[Authorize]` cannot be turned into a response. `ChallengeAsync` throws `InvalidOperationException`: "No authenticationScheme was specified, and there was no DefaultChallengeScheme found." ## Doing it yourself in imperative checks When a handler calls `IAuthorizationService.AuthorizeAsync` itself, for example to check a document it has just loaded, the framework is no longer choosing. You apply the same rule: - user authenticated: return `Forbid()` from a controller, or `Results.Forbid()` / `TypedResults.Forbid()` from a Minimal API; - user not authenticated: return `Challenge()` or `Results.Challenge()`. Returning `Unauthorized()` writes a bare `401` without involving any scheme, so a cookie app gets no redirect and a bearer API gets no `WWW-Authenticate` header. ## Customising the response There are two layers to change: - **The scheme's events.** `JwtBearerEvents.OnChallenge` and `OnForbidden`, or the cookie's `OnRedirectToLogin` and `OnRedirectToAccessDenied`, change how that scheme answers everywhere. - **The middleware's result handler.** Register your own `IAuthorizationMiddlewareResultHandler` to see the failed policy and the `AuthorizationFailure`, for example to return `404` instead of `403` for documents whose existence should not leak. Delegate the remaining cases to an `AuthorizationMiddlewareResultHandler` instance. ## Diagnosing a wrong status code When a client reports the "wrong" response, walk the decision in order: 1. Did authentication succeed? Check `HttpContext.User.Identity.IsAuthenticated` for the policy's schemes; an expired or unreadable token means challenge, never forbid. 2. Which scheme answered? The policy's `AuthenticationSchemes` win, then the default challenge or forbid scheme. A cookie scheme as the default on an API produces redirects. 3. Did hand-written code short-circuit the scheme? Look for `Unauthorized()`, `StatusCode(403)` or `Results.StatusCode(...)` after an imperative check. 4. Did a custom result handler or scheme event rewrite the response? Search for `IAuthorizationMiddlewareResultHandler` registrations and `OnRedirectToLogin` overrides. ## Why the distinction matters Clients act on the code. A `401` tells a single-page app to refresh its token or send the user to sign in; a `403` tells it to stop retrying and show "no access". Mixing them up either sends signed-in users round a sign-in loop or leaves an expired session showing "forbidden".
- A cookie-authenticated app shows a sign-in page to users who are already signed in but lack a role. What is likely wrong?The forbid is being treated as a challenge. Typically `AccessDeniedPath` points at the login page, or an imperative check returns `Challenge()` for an authenticated user instead of `Forbid()`. The middleware itself forbids authenticated users, so look at the scheme's paths and any hand-written results.
- How would you return 404 instead of 403 when a user may not see a contract?Register a custom `IAuthorizationMiddlewareResultHandler` that, when `authorizeResult.Forbidden` is true for that policy, sets `404` and returns, and otherwise calls an `AuthorizationMiddlewareResultHandler` instance. For imperative checks, simply return `NotFound()` when `AuthorizeAsync` fails.
- The authentication middleware returns 401 for anonymous requests on its own.
- A failed policy always returns 403, whether or not the user signed in.
- Returning Unauthorized() is the same as returning Challenge().
- The cookie handler always redirects to the login page, even for API endpoints in .NET 10.
- A 401 means the user lacks the required role.
Assumes ASP.NET Core 10; from 10 the cookie handler answers 401/403 instead of redirecting for endpoints marked as API endpoints.