In ASP.NET Core 10, why does an unauthenticated call to a cookie-protected [ApiController] action get 401 instead of a redirect to LoginPath, and how do you control it?
answer
- challenge vs forbid in the cookie handler
- IDisableCookieRedirectMetadata on API endpoints
- Location header still sent
- AllowCookieRedirect overrides it
- IgnoreRedirectMetadata app-context switch
basics
~10 sSince ASP.NET Core 10, the cookie handler's default OnRedirectToLogin and OnRedirectToAccessDenied answer 401 or 403 instead of redirecting when the endpoint carries IDisableCookieRedirectMetadata, which [ApiController], JSON Minimal APIs, TypedResults and SignalR add automatically.
solid answer
~40 sAuthorization challenges through the cookie scheme, and the cookie handler hands the decision to `CookieAuthenticationEvents.OnRedirectToLogin` (403 cases go to `OnRedirectToAccessDenied`). Before 10 the defaults redirected every request except those sent with `X-Requested-With: XMLHttpRequest`. In ASP.NET Core 10 they also return 401 or 403 when the endpoint has `IDisableCookieRedirectMetadata`, which `[ApiController]`, Minimal API endpoints that read or write JSON, `TypedResults` return types and SignalR endpoints add for you. The `Location` header still carries the login URL; only the status changes. Opt a single endpoint back in with `[AllowCookieRedirect]` or `.AllowCookieRedirect()`, opt one out with `.DisableCookieRedirect()`, restore the old behaviour app-wide with the `Microsoft.AspNetCore.Authentication.Cookies.IgnoreRedirectMetadata` switch, or replace the event handlers outright.
code
csharp · 13 linesvar portal = app.MapGroup("/portal").RequireAuthorization();
// Returns a JSON-serialized type: cookie challenge answers 401 with a Location header.
portal.MapGet("/api/grades", (GradeBook book, ClaimsPrincipal user) => book.For(user));
// Declared IResult and no JSON body: still redirected, so opt out explicitly.
portal.MapGet("/api/report-card", (ReportCards cards, ClaimsPrincipal user) =>
Results.File(cards.Pdf(user), "application/pdf"))
.DisableCookieRedirect();
// Opt a JSON-returning endpoint back in to the browser redirect.
portal.MapGet("/welcome-summary", (Summaries s, ClaimsPrincipal user) => s.For(user))
.AllowCookieRedirect();go deeper
Know that a browser page behind cookie auth redirects to the login page, and that in ASP.NET Core 10 an API endpoint answers 401 instead.
Explain that authorization triggers the challenge, that the cookie handler's OnRedirectToLogin decides redirect versus status, and which endpoints count as APIs.
Plan the upgrade: find clients that relied on following the redirect, update tests that expected 302, and use AllowCookieRedirect, DisableCookieRedirect or the switch where inference is wrong.
Decide whether one app should still mix browser pages and API endpoints under one cookie scheme, or give APIs their own scheme so challenges never depend on endpoint inference.
## Where the redirect comes from Authentication middleware never rejects a request. When an endpoint requires an authenticated user and `HttpContext.User` is anonymous, the **authorization** middleware calls `ChallengeAsync` on the endpoint's scheme (or the default challenge scheme). For an authenticated user who fails a policy it calls `ForbidAsync`. With the cookie scheme those calls reach `CookieAuthenticationHandler`: - a challenge builds `LoginPath?ReturnUrl=<original path>` and raises `OnRedirectToLogin`; - a forbid builds `AccessDeniedPath?ReturnUrl=...` and raises `OnRedirectToAccessDenied`. The **default event handlers** decide between a 302 and a status code. That is the piece that changed. ## Before ASP.NET Core 10 The default handlers returned 401 (challenge) or 403 (forbid) only for an "AJAX" request, recognised by an `X-Requested-With: XMLHttpRequest` header or query value. Everything else, including a `fetch` call from a single-page app or a partner's HTTP client, received `302 Found` to the login page and then `200 OK` with HTML. API clients saw a successful HTML response instead of a 401, which produced confusing parse errors. Teams worked around it by overriding `OnRedirectToLogin`. ## What ASP.NET Core 10 does The default handlers now also return the status code when the endpoint's metadata contains `IDisableCookieRedirectMetadata` and does **not** contain `IAllowCookieRedirectMetadata`. That metadata is added automatically to: | Endpoint kind | Why it counts as an API | |---|---| | controllers with `[ApiController]` | the attribute implements `IDisableCookieRedirectMetadata` | | Minimal API handlers that bind a JSON body | the request delegate factory infers an API endpoint | | Minimal API handlers that return a JSON-serialized type | same inference, from the return type | | handlers returning `TypedResults` types such as `Ok<T>` | the result types add the metadata | | SignalR hub endpoints | the connection endpoints add it | Points worth knowing precisely: - The **`Location` header is still set** to the login or access-denied URL; only the status code changes from 302 to 401 or 403. - Only the **challenge and forbid** paths look at the metadata. Sign-out redirects and the return-URL redirect after sign-in are unaffected. - A Minimal API handler whose declared return type is plain `IResult` (for example `Results.Ok(...)`) and that binds no JSON body gets no inferred metadata and keeps redirecting. ## Controlling it 1. **Per endpoint, back to redirects**: `[AllowCookieRedirect]` or `.AllowCookieRedirect()`. Allow wins over disable regardless of the order the metadata was added. 2. **Per endpoint, to status codes**: `.DisableCookieRedirect()` on an endpoint the inference missed. 3. **Whole app, pre-10 behaviour**: the `Microsoft.AspNetCore.Authentication.Cookies.IgnoreRedirectMetadata` switch, set as a `RuntimeHostConfigurationOption` in the project file or with `AppContext.SetSwitch` before the host is built. It is read once, the first time the events type is used. 4. **Full control**: assign your own `OnRedirectToLogin` and `OnRedirectToAccessDenied` delegates; they replace the defaults, so the metadata check no longer runs. ## Why it matters for an upgrade A portal that mixed Razor Pages for parents with `[ApiController]` endpoints for its own JavaScript usually wanted exactly this, and can delete a custom `OnRedirectToLogin`. An app whose JavaScript **followed** the redirect and parsed the login page will break: it now gets a 401 with a `Location` header and must navigate itself. Integration tests that asserted `302` on API routes need updating to `401`. ## Checking which behaviour an endpoint gets - Inspect the endpoint's metadata (for example in a test, through `EndpointDataSource`) for `IDisableCookieRedirectMetadata` and `IAllowCookieRedirectMetadata`. - Remember that the decision is made in the **default** `OnRedirectToLogin` and `OnRedirectToAccessDenied`; any custom delegate assigned to those events bypasses it entirely. - Check the `X-Requested-With` header too: requests carrying `XMLHttpRequest` there still get 401 or 403 on every endpoint, as before.
- After the upgrade, the portal's JavaScript gets a 401 where it used to land on the login page. What is the cleanest client-side fix?Treat 401 as 'session expired': read the `Location` header the handler still sends, or a known login URL, and navigate the window there, preserving the current page as the return URL. That is more robust than following a 302 and parsing HTML, which was the accidental behaviour before ASP.NET Core 10.
- An app already overrides OnRedirectToLogin to return 401 for paths starting with /api. Does the .NET 10 change affect it?No. A custom delegate replaces the default event handler, and the metadata check lives only in the defaults. The override keeps working as written; it could now be deleted in favour of the built-in behaviour if its path rule matches the API endpoints.
- The authentication middleware itself returns 401 for anonymous requests to API endpoints.
- In .NET 10 the 401 from cookie authentication no longer carries a Location header.
- Every endpoint behind cookie authentication stops redirecting to LoginPath in .NET 10.
- Only requests with X-Requested-With: XMLHttpRequest can ever get a 401 from cookie authentication.
- Setting LoginPath to null is the supported way to get 401s for APIs.
Assumes ASP.NET Core 10, where cookie authentication started honouring IDisableCookieRedirectMetadata; on 8 and 9 the same API endpoints received a 302 to LoginPath.