Skip to content

Commit d6c4040

Browse files
authored
WN: Prev7: Add include: Avoid Cookie Login on API endpoint (#35906)
1 parent 7db6835 commit d6c4040

File tree

1 file changed

+36
-0
lines changed

1 file changed

+36
-0
lines changed
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
### Avoid cookie login redirects for known API endpoints
2+
3+
By default, unauthenticated and unauthorized requests made to known API endpoints protected by cookie authentication now result in 401 and 403 responses rather than redirecting to a login or access denied URI.
4+
5+
This change was [highly requested](https://github.com/dotnet/aspnetcore/issues/9039), because redirecting unauthenticated requests to a login page doesn't usually make sense for API endpoints which typically rely on 401 and 403 status codes rather than HTML redirects to communicate auth failures.
6+
7+
Known API [Endpoints](https://learn.microsoft.com/aspnet/core/fundamentals/routing) are identified using the new `IApiEndpointMetadata` interface, and metadata implementing the new interface has been added automatically to the following:
8+
9+
- `[ApiController]` endpoints
10+
- Minimal API endpoints that read JSON request bodies or write JSON responses
11+
- Endpoints using `TypedResults` return types
12+
- SignalR endpoints
13+
14+
When `IApiEndpointMetadata` is present, the cookie authentication handler now returns appropriate HTTP status codes (401 for unauthenticated requests, 403 for forbidden requests) instead of redirecting.
15+
16+
If you want to prevent this new behavior, and always redirect to the login and access denied URIs for unauthenticated or unauthorized requests regardless of the target endpoint, you can override the `RedirectToLogin` and `RedirectToAccessDenied` events as follows:
17+
18+
```csharp
19+
builder.Services.AddAuthentication()
20+
.AddCookie(options =>
21+
{
22+
options.Events.OnRedirectToLogin = context =>
23+
{
24+
context.Response.Redirect(context.RedirectUri);
25+
return Task.CompletedTask;
26+
};
27+
28+
options.Events.OnRedirectToAccessDenied = context =>
29+
{
30+
context.Response.Redirect(context.RedirectUri);
31+
return Task.CompletedTask;
32+
};
33+
});
34+
```
35+
36+
For more information about this breaking change, see [ASP.NET Core breaking changes announcement](https://github.com/aspnet/Announcements/issues/525).

0 commit comments

Comments
 (0)