dotnet / dotnet/aspnetcore

When adding AuthN/Z, check if middleware is already added

Open
#53,760 10 comments 0 reactions 1 assignee Claimed by @halter73 View on GitHub
analyzer area-auth enhancement
Dominant language
C#
Stars
38.4k
Forks
10.9k
Avg merge
2d 6h
Merged PRs (30d)
290

Description

### Is there an existing issue for this?

- [X] I have searched the existing issues

### Describe the bug

Issue #47664 automatically adds AuthN/Z middleware if services are registered. If UseAuthentication or UseAuthorization are called manually in the configuration process, it creates an error scenario indicating issues with Antiforgery.

Can we add a check in UseAuthN/Z to prevent duplicate middleware addition?

https://github.com/dotnet/aspnetcore/blob/main/src/Security/Authentication/Core/src/AuthAppBuilderExtensions.cs#L20
https://github.com/dotnet/aspnetcore/blob/main/src/Security/Authorization/Policy/src/AuthorizationAppBuilderExtensions.cs#L26

### Expected Behavior

Executing UseAuthentication / UseAuthorization should not trigger an antiforgery error

### Steps To Reproduce

Update the default template to include:

```csharp
app.UseStaticFiles();
app.UseAntiforgery();

// new lines
app.UseAuthentication();
app.UseAuthorization();
```

Register and login as a new user and then attempt to logout

### Exceptions (if any)

```
Microsoft.AspNetCore.Antiforgery.AntiforgeryValidationException: The provided antiforgery token was meant for a different claims-based user than the current user.

at Microsoft.AspNetCore.Antiforgery.DefaultAntiforgery.ValidateTokens(HttpContext httpContext, AntiforgeryTokenSet antiforgeryTokenSet)

at Microsoft.AspNetCore.Antiforgery.DefaultAntiforgery.ValidateRequestAsync(HttpContext httpContext)

at Microsoft.AspNetCore.Antiforgery.Internal.AntiforgeryMiddleware.InvokeAwaited(HttpContext context)
```

### .NET Version

8.0.1

### 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.