On ASP.NET Core 10.0.15, an anonymous call to a minimal API endpoint that returns JSON and sits behind cookie authentication answered 302 Found with a Location pointing at the login page, even with Accept: application/json. Only a request carrying X-Requested-With: XMLHttpRequest got 401 Unauthorized. To make API paths answer 401, handle OnRedirectToLogin in the cookie options.

A client that gets a 302 instead of a 401 has no status to act on; one that follows the redirect gets whatever the login path serves (for this app's page endpoint, curl with -L ended in a 404). The event below sets 401 for paths under /api and keeps the redirect for pages.

The error

PS> curl.exe -s -i -H "Accept: application/json" http://127.0.0.1:15610/api/reports | Select-String -Pattern '^HTTP|^Location'
HTTP/1.1 302 Found
Location: http://127.0.0.1:15610/Account/Login?ReturnUrl=%2Fapi%2Freports
PS> curl.exe -s -i -H "X-Requested-With: XMLHttpRequest" http://127.0.0.1:15610/api/reports | Select-String -Pattern '^HTTP|^Location'
HTTP/1.1 401 Unauthorized
Location: http://127.0.0.1:15610/Account/Login?ReturnUrl=%2Fapi%2Freports

Each command keeps only the status line and the Location header through its Select-String pipe; the lines were rerun in that form from the same build, started the same way as the first run. The 401 still carried a Location header.

Why it happens

...
app.MapGet("/reports", () => Results.Content("<h1>Reports</h1>", "text/html")).RequireAuthorization();
app.MapGet("/api/reports", () => Results.Json(new { count = 3 })).RequireAuthorization();
...

The test sent three kinds of anonymous request to a page endpoint and to a JSON endpoint: a browser-style Accept: text/html, an API-style Accept: application/json, and X-Requested-With: XMLHttpRequest. Both endpoints behaved the same: 302 for the first two, 401 for the third. Returning Results.Json and asking for JSON did not change the answer; in this test only the X-Requested-With header did. Other ways of declaring an API endpoint were not tried.

The fix

...
        if (builder.Configuration["ApiStatus"] == "true")
        {
            options.Events.OnRedirectToLogin = context =>
            {
                if (context.Request.Path.StartsWithSegments("/api"))
                {
                    context.Response.StatusCode = StatusCodes.Status401Unauthorized;
                    return Task.CompletedTask;
                }
                context.Response.Redirect(context.RedirectUri);
                return Task.CompletedTask;
            };
        }
...
started pid 32348: dotnet bin\Debug\net10.0\AfLab.dll --urls http://127.0.0.1:15610 --environment Development --Keys keys-a --LoginPath /sign-in --ApiStatus true
PS> curl.exe -s -i -H "Accept: application/json" http://127.0.0.1:15610/api/reports | Select-String -Pattern '^HTTP|^Location'
HTTP/1.1 401 Unauthorized
PS> curl.exe -s -i -H "X-Requested-With: XMLHttpRequest" http://127.0.0.1:15610/api/reports | Select-String -Pattern '^HTTP|^Location'
HTTP/1.1 401 Unauthorized
PS> curl.exe -s -i -H "Accept: application/json" http://127.0.0.1:15610/reports | Select-String -Pattern '^HTTP|^Location'
HTTP/1.1 302 Found
Location: http://127.0.0.1:15610/sign-in?ReturnUrl=%2Freports
PS> curl.exe -s -c jar2.txt "http://127.0.0.1:15610/login?user=maria"
Signed in as maria.
PS> curl.exe -s -i -b jar2.txt -H "Accept: application/json" http://127.0.0.1:15610/api/reports | Select-String -Pattern '^HTTP|count'
HTTP/1.1 200 OK
{"count":3}

With the event in place, /api/reports answered 401 with no Location, the page /reports still redirected (to /sign-in, the run's LoginPath), and a signed-in request with the cookie from the test's /login endpoint got 200 and the JSON. The lab wraps the event in a command-line switch; it was added and the app rebuilt between the first run and the fixed one, and both runs shown in this post were then repeated from that one build. AfLab, port 15610, the /api prefix, the routes /reports, /api/reports, /login and /sign-in, the file jar2.txt, the user maria and the switches are the test's own.

How it was reproduced

A project from dotnet new web -n AfLab -f net10.0 on .NET SDK 11.0.100, no NuGet packages, running on ASP.NET Core 10.0.15 in Development on 127.0.0.1:15610, with AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme).AddCookie(...), AddAuthorization() and the two endpoints above. Requests went through curl 8.22.0 without a cookie, one per path and header, except the last, which used a cookie jar from a test sign-in.

Frequently asked

Does ASP.NET Core 10 cookie authentication return 401 for API calls?
Not for the minimal API JSON endpoint in this test on 10.0.15: with Accept application/json it answered 302 to the login page. Only a request with X-Requested-With XMLHttpRequest got 401.
How do I return 401 instead of redirecting to login in ASP.NET Core?
Handle options.Events.OnRedirectToLogin in AddCookie and set StatusCode 401 for API paths, keeping the redirect for pages. In the test /api/reports then answered 401 and /reports still redirected.
Why does my API answer 302 instead of 401?
In the test an anonymous request with Accept application/json was answered with a 302 to the login page. Sending X-Requested-With XMLHttpRequest, or the OnRedirectToLogin change, gave a 401 instead.

More decoded errors in the Fixes category. When the redirect itself ends in a 404, see /Account/Login?ReturnUrl answers 404.