aspnetcore/security/authentication/api-endpoint-auth.md
:::moniker range=">= aspnetcore-10.0"
When using cookie authentication, API endpoints return the appropriate HTTP status codes (such as 401 or 403) for authentication failures instead of redirecting unauthenticated requests to login pages. This behavior, which is more suitable for programmatic API access, was introduced in ASP.NET Core in .NET 10.
ASP.NET Core automatically applies this behavior to endpoints it recognizes as API-related, including:
[ApiController] attributeMapGet, MapPost, MapPut, MapDelete, etc.By default, ASP.NET Core applies cookie authentication logic based on the endpoint type:
While the default behavior works for most scenarios, it can be customized if needed:
builder.Services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
.AddCookie(options =>
{
options.LoginPath = "/Account/Login";
// The framework automatically handles API endpoints
// No additional configuration needed
});
If you need to override the automatic detection for specific endpoints, use the [Authorize] attribute with specific authentication schemes or implement custom authentication handlers.
This behavior change introduced in .NET 10 is designed to be non-breaking for existing applications:
After upgrading to ASP.NET Core 10, verify that your API endpoints return appropriate status codes:
[Test]
public async Task UnauthorizedApiRequest_Returns401()
{
var response = await client.GetAsync("/api/secure-data");
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
Assert.False(response.Headers.Location != null); // No redirect
}
:::moniker-end