.NET 7 UseAuthentication and UserAuthorization ordering not respected when within UseWhen
- Dominant language
- C#
- Stars
- 38.4k
- Forks
- 10.9k
- Avg merge
- 2d 10h
- Merged PRs (30d)
- 281
Description
### Is there an existing issue for this?
- [X] I have searched the existing issues
### Describe the bug
When configuring my WebApplication I make use of a UseWhen statement so that auth logic is only applied to endpoints with a specific base path.
This worked with ASP.NET Core 6.0 but with 7.0 there are two problems:
1. Auth is applied to all endpoints.
2. Auth middleware runs before all other middleware.
I believe this to be caused by the new 7.0 feature that automatically calls UseAuthentication and UseAuthorization when AddAuthentication / AddAuthorization are called. I see there is code in place to prevent this if it is detected that UseAuthentication / UseAuthentication have already been called, but this does not appear to take UseWhen into account.
### Expected Behavior
Auth middleware is not inserted when already inserted within a UseWhen statement.
### Steps To Reproduce
```
app.UseWhen(
httpContext => httpContext.Request.Path.StartsWithSegments("/api"),
subApp =>
{
subApp.UseAuthentication();
subApp.UseAuthorization();
});
```
### Exceptions (if any)
_No response_
### .NET Version
7.0.203
### Anything else?
_No response_
Contributor guide
Assessment
This issue has not been assessed yet.