dotnet / dotnet/aspnetcore

.NET 7 UseAuthentication and UserAuthorization ordering not respected when within UseWhen

Open
#48,098 12 comments 4 reactions 0 assignees View on GitHub
area-minimal bug feature-minimal-hosting
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

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.