
ASP.NET CoreAuthenticationCookiesAPI Security.NET 10
9/2/2025
In current versions of ASP.NET Core (.NET 6 / 7 / 8), when using Cookie Authentication to protect APIs, unauthenticated or unauthorized requests are not always handled in a way that fits API scenarios. This behavior changes officially starting with .NET 10.
Before this new behavior becomes the default in .NET 10, you can customize Cookie Authentication Events to return the correct status codes for API requests.
This solution relies on endpoint metadata to detect API controllers.
builder.Services.AddIdentityCookies(o =>
{
o.ApplicationCookie.Configure(options =>
{
options.Cookie.Name = "CookieName";
options.LoginPath = "/Account/Login";
options.AccessDeniedPath = "/Account/AccessDenied";
...
options.Events.OnRedirectToLogin = context =>
{
if (IsApiControllerEndpoint(context))
{
context.Response.StatusCode = StatusCodes.Status401Unauthorized;
}
else
{
context.Response.Redirect(context.RedirectUri);
}
return Task.CompletedTask;
};
options.Events.OnRedirectToAccessDenied = context =>
{
if (IsApiControllerEndpoint(context))
{
context.Response.StatusCode = StatusCodes.Status403Forbidden;
}
else
{
context.Response.Redirect(context.RedirectUri);
}
return Task.CompletedTask;
};
});
});
private static bool IsApiControllerEndpoint(RedirectContext<CookieAuthenticationOptions> context)
{
var endpoint = context.HttpContext.GetEndpoint();
if (endpoint == null)
return false;
// Detect API endpoints via [ApiController] attribute
return endpoint.Metadata.GetMetadata<ApiControllerAttribute>() != null;
}
[ApiController]
) → return 401 or 403.[ApiController]
detection works for MVC and Web API controllers.
Minimal APIs and SignalR hubs may need extra handling using:
IApiEndpointMetadata
TypedResults
Testing is essential to confirm: