-
Notifications
You must be signed in to change notification settings - Fork 25.1k
Add documentation for .NET 10 API endpoint authentication behavior changes #35895
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
Copilot
wants to merge
17
commits into
main
Choose a base branch
from
copilot/fix-35894
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+104
−0
Open
Changes from 7 commits
Commits
Show all changes
17 commits
Select commit
Hold shift + click to select a range
659fc53
Initial plan
Copilot 941bbdf
Add API endpoint authentication behavior documentation for .NET 10
Copilot f99f5dd
Update placement of API endpoint authentication include based on feed…
Copilot f406310
Update responses.md
wadepickett d7a6d21
Update cookie.md
wadepickett 14ca824
Update authn-and-authz.md
wadepickett b77a554
Update index.md
wadepickett ec7ac78
Update aspnetcore/security/authentication/api-endpoint-auth.md
wadepickett f952406
Update api-endpoint-auth.md
wadepickett fb17d5c
Update api-endpoint-auth.md
wadepickett 70f099f
Update cookie.md
wadepickett 78b9b85
Update authn-and-authz.md
wadepickett ab8fe13
Update authn-and-authz.md
wadepickett c145539
Update index.md
wadepickett 0ba455c
Update api-endpoint-auth.md
wadepickett d490352
Update authn-and-authz.md
wadepickett 636a0e5
Add API endpoint auth doc to TOC and improve wording
Copilot File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,2 @@ | ||
> [!IMPORTANT] | ||
> Starting with ASP.NET Core 10, known API endpoints no longer redirect to login pages when using cookie authentication. Instead, they return 401/403 status codes. For details, see <xref:security/authentication/api-endpoint-auth>. |
109 changes: 109 additions & 0 deletions
109
aspnetcore/security/authentication/api-endpoint-auth.md
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,109 @@ | ||
--- | ||
title: API endpoint authentication behavior in ASP.NET Core | ||
author: wadepickett | ||
description: Learn how ASP.NET Core 10 and later handles authentication failures for API endpoints using cookie authentication. | ||
ai-usage: ai-assisted | ||
monikerRange: '>= aspnetcore-10.0' | ||
ms.author: wpickett | ||
ms.date: 08/06/2025 | ||
uid: security/authentication/api-endpoint-auth | ||
--- | ||
|
||
# API endpoint authentication behavior in ASP.NET Core | ||
|
||
:::moniker range=">= aspnetcore-10.0" | ||
|
||
Starting with ASP.NET Core 10, the framework introduces a significant improvement in how authentication failures are handled for API endpoints when using cookie authentication. This change addresses the common issue where API endpoints would redirect unauthenticated requests to login pages, which is inappropriate for programmatic API access. | ||
|
||
## The problem | ||
|
||
In previous versions of ASP.NET Core, when using cookie authentication, all unauthenticated requests would trigger a redirect to the configured login page. This behavior was problematic for API endpoints because: | ||
|
||
- API clients don't expect HTML login pages | ||
- Redirects return 302 status codes instead of proper 401/403 codes | ||
- API clients need clear HTTP status codes to handle authentication failures appropriately | ||
|
||
## The solution in ASP.NET Core 10 | ||
|
||
ASP.NET Core 10 automatically detects known API endpoints and modifies the authentication behavior: | ||
|
||
- **Web pages**: Continue to redirect to login pages as before | ||
- **API endpoints**: Return appropriate 401 (Unauthorized) or 403 (Forbidden) status codes without redirects | ||
|
||
## Which endpoints are considered API endpoints? | ||
|
||
The framework automatically identifies the following as API endpoints: | ||
|
||
- Controllers decorated with `[ApiController]` attribute | ||
- Minimal API endpoints registered with `MapGet`, `MapPost`, `MapPut`, `MapDelete`, etc. | ||
- Endpoints that explicitly request JSON responses | ||
- SignalR hubs and endpoints | ||
|
||
## Behavior differences | ||
|
||
### Before ASP.NET Core 10 | ||
|
||
```http | ||
GET /api/secure-data HTTP/1.1 | ||
Host: example.com | ||
|
||
HTTP/1.1 302 Found | ||
Location: /Account/Login?ReturnUrl=%2Fapi%2Fsecure-data | ||
``` | ||
|
||
### ASP.NET Core 10 and later | ||
|
||
```http | ||
GET /api/secure-data HTTP/1.1 | ||
Host: example.com | ||
|
||
HTTP/1.1 401 Unauthorized | ||
WWW-Authenticate: Cookie | ||
``` | ||
|
||
## Configuring the behavior | ||
|
||
While the default behavior works for most scenarios, you can customize it if needed: | ||
|
||
```csharp | ||
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, you can use the `[Authorize]` attribute with specific authentication schemes or implement custom authentication handlers. | ||
|
||
## Migration considerations | ||
|
||
This change is designed to be non-breaking for existing applications: | ||
|
||
- **Web applications**: Continue to work as before with login page redirects | ||
- **Mixed applications**: API endpoints get proper status codes while web pages get redirects | ||
- **API-only applications**: Benefit from proper HTTP status codes without additional configuration | ||
|
||
### Testing your API endpoints | ||
|
||
After upgrading to ASP.NET Core 10, verify that your API endpoints return appropriate status codes: | ||
|
||
```csharp | ||
[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 | ||
} | ||
``` | ||
|
||
## Related topics | ||
|
||
- <xref:security/authentication/cookie> | ||
- <xref:web-api/index> | ||
- <xref:fundamentals/minimal-apis/responses> | ||
- <xref:signalr/authn-and-authz> | ||
|
||
:::moniker-range-end |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -19,6 +19,10 @@ By [Rick Anderson](https://twitter.com/RickAndMSFT) | |
|
||
For demonstration purposes in the sample app, the user account for the hypothetical user, Maria Rodriguez, is hardcoded into the app. Use the **Email** address `[email protected]` and any password to sign in the user. The user is authenticated in the `AuthenticateUser` method in the `Pages/Account/Login.cshtml.cs` file. In a real-world example, the user would be authenticated against a datastore. | ||
|
||
:::moniker range=">= aspnetcore-10.0" | ||
[!INCLUDE[](~/includes/api-endpoint-auth.md)] | ||
:::moniker-end | ||
|
||
## Add cookie authentication | ||
|
||
* Add the Authentication Middleware services with the <xref:Microsoft.Extensions.DependencyInjection.AuthenticationServiceCollectionExtensions.AddAuthentication%2A> and <xref:Microsoft.Extensions.DependencyInjection.CookieExtensions.AddCookie%2A> methods. | ||
|
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.