Description
Is there an existing issue for this?
- 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:
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