Skip to content

Remove redundant app.UseAntiforgery() from Blazor Web templates#67119

Merged
DeagleGross merged 5 commits into
dotnet:mainfrom
DeagleGross:deaglegross/remove-useantiforgery-from-templates
Jun 25, 2026
Merged

Remove redundant app.UseAntiforgery() from Blazor Web templates#67119
DeagleGross merged 5 commits into
dotnet:mainfrom
DeagleGross:deaglegross/remove-useantiforgery-from-templates

Conversation

@DeagleGross

@DeagleGross DeagleGross commented Jun 10, 2026

Copy link
Copy Markdown
Member

CSRF protection is now on by default via the auto-injected CsrfProtectionMiddleware (Fetch Metadata based, #65127), so the explicit app.UseAntiforgery() in the Blazor Web templates is redundant. This removes it from both variants (Program.cs and Program.Main.cs).

Why the middleware change is needed

EndpointMiddleware throws "a middleware was not found that supports anti-forgery" when an endpoint requires antiforgery but no antiforgery middleware recorded that it ran (a marker in HttpContext.Items). With UseAntiforgery() gone, the auto-injected CsrfProtectionMiddleware is the only thing that can set that marker — but it previously set it only when an endpoint was already matched.

That breaks re-execute: UseStatusCodePagesWithReExecute / UseExceptionHandler re-run the request through a fresh routing branch that bypasses the auto-injected middleware, so it only runs once on the original request. If that request is a 404 (no endpoint) or hits a DisableAntiforgery() endpoint, the marker never gets set, and re-executing into an antiforgery-required page (e.g. a Razor Component) throws.

Both Program.cs (top-level) and Program.Main.cs variants of the BlazorWeb-CSharp template no longer need the explicit call: CsrfProtectionMiddleware (auto-injected by WebApplication) handles cross-site request protection via Sec-Fetch-Site/Origin, and the Razor Components endpoint invoker no longer self-validates token-based antiforgery when the new CSRF middleware ran.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Copilot AI review requested due to automatic review settings June 10, 2026 10:48
@github-actions github-actions Bot added the area-mvc Includes: MVC, Actions and Controllers, Localization, CORS, most templates label Jun 10, 2026

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

This PR removes the explicit app.UseAntiforgery(); call from the Blazor Web C# template’s two Program.cs variants, intending to rely on the newer CSRF middleware behavior instead of the legacy antiforgery middleware.

Changes:

  • Removed app.UseAntiforgery(); from the top-level statements template Program.cs.
  • Removed app.UseAntiforgery(); from the Main-style template Program.Main.cs.
Show a summary per file
File Description
src/ProjectTemplates/Web.ProjectTemplates/content/BlazorWeb-CSharp/BlazorWebCSharp.1/Program.cs Removes UseAntiforgery() from the template pipeline.
src/ProjectTemplates/Web.ProjectTemplates/content/BlazorWeb-CSharp/BlazorWebCSharp.1/Program.Main.cs Removes UseAntiforgery() from the template pipeline (Main-style).

Copilot's findings

  • Files reviewed: 2/2 changed files
  • Comments generated: 2

@DeagleGross

Copy link
Copy Markdown
Member Author

test failure in aspnetcore-template-tests-pr also related to #67174

@DeagleGross
DeagleGross merged commit 52734f5 into dotnet:main Jun 25, 2026
25 checks passed
@DeagleGross
DeagleGross deleted the deaglegross/remove-useantiforgery-from-templates branch June 25, 2026 17:32
@dotnet-milestone-bot dotnet-milestone-bot Bot added this to the 11.0-preview7 milestone Jun 26, 2026
@BrennanConroy

Copy link
Copy Markdown
Member

This change hurts perf for non-endpoint code paths. e.g. Our plaintext benchmarks now allocate billions of bytes per second instead of a previous ~5m bytes per second.

context.Items is lazily initialized, so by accessing it every time a request comes in creates a bunch of extra allocations:
image

@DeagleGross

Copy link
Copy Markdown
Member Author

Thanks for noticing this Brennan, here is the fix: #67488

DeagleGross added a commit that referenced this pull request Jul 8, 2026
Under the default-on CsrfProtectionMiddleware (with app.UseAntiforgery()
removed by #67119), the hidden __RequestVerificationToken fields rendered
by <AntiforgeryToken /> are never validated. Blazor SSR form binding and
minimal-API [FromForm] parameters auto-attach IAntiforgeryMetadata, so
those endpoints stay CSRF-protected by the new middleware.

- Remove 12 dead <AntiforgeryToken /> components across 10 razor files.
- Add explicit [RequireAntiforgeryToken] to /DownloadPersonalData
  (JSON minimal-API POST with no [FromForm] auto-attach).

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
DeagleGross added a commit that referenced this pull request Jul 10, 2026
* Fix Blazor passkey antiforgery template flow

Co-authored-by: javiercn <6995051+javiercn@users.noreply.github.com>

* Add antiforgery metadata to passkey endpoints

Co-authored-by: javiercn <6995051+javiercn@users.noreply.github.com>

* Honor antiforgery validation in passkey endpoints

Co-authored-by: javiercn <6995051+javiercn@users.noreply.github.com>

* Remove redundant passkey antiforgery test

Co-authored-by: javiercn <6995051+javiercn@users.noreply.github.com>

* Restore UTF-8 BOM on PasskeySubmit.razor

The scaffolded Blazor template requires all .razor files under Web.ProjectTemplates/content to be UTF-8-BOM-encoded (enforced by ByteOrderMarkTest.RazorFilesInWebProjects_ShouldContainBOM). The rewrite in this PR stripped the BOM; restore it.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>

* Eliminate dead antiforgery markup from BlazorWeb-CSharp template

Under the default-on CsrfProtectionMiddleware (with app.UseAntiforgery()
removed by #67119), the hidden __RequestVerificationToken fields rendered
by <AntiforgeryToken /> are never validated. Blazor SSR form binding and
minimal-API [FromForm] parameters auto-attach IAntiforgeryMetadata, so
those endpoints stay CSRF-protected by the new middleware.

- Remove 12 dead <AntiforgeryToken /> components across 10 razor files.
- Add explicit [RequireAntiforgeryToken] to /DownloadPersonalData
  (JSON minimal-API POST with no [FromForm] auto-attach).

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>

* Enforce CSRF verdict on /DownloadPersonalData endpoint

This endpoint reads no form body ([FromServices] only), so neither
FormFeature nor RequestDelegateFactory form binding will reject on a
failed IAntiforgeryValidationFeature verdict. Add an explicit check
matching the pattern used by the sibling PasskeyCreationOptions and
PasskeyRequestOptions endpoints, so cross-site POSTs are rejected
with 400 instead of silently returning the user's personal data.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>

* Fail closed on missing IAntiforgeryValidationFeature

Switch the three explicit-check endpoints (PasskeyCreationOptions,
PasskeyRequestOptions, DownloadPersonalData) from `is { IsValid: false }`
to `is not { IsValid: true }` so that a null feature (e.g. when
CsrfProtectionMiddleware is skipped for any reason) is also rejected.
The endpoints explicitly opted in via [RequireAntiforgeryToken], so
proceeding without a validated verdict would violate that intent.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>

* Fix CS0165 on IAntiforgeryValidationFeature pattern check

The prior commit used `is not { IsValid: true } antiforgeryValidationFeature`
which does not definitely-assign the pattern variable in the negated
branch. Extract the feature into an explicit local before the check to
compile cleanly and keep fail-closed semantics on null / IsValid=false.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>

---------

Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com>
Co-authored-by: javiercn <6995051+javiercn@users.noreply.github.com>
Co-authored-by: Dmitry Korolev <dmkorolev@microsoft.com>
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area-mvc Includes: MVC, Actions and Controllers, Localization, CORS, most templates

Projects

None yet

Development

Successfully merging this pull request may close these issues.

6 participants