Skip to content

[Blazor] Emit antiforgery only when streaming, a form has been placed on the page or there are interactive render modes configured #62653

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 4 commits into from
Jul 10, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -10,10 +10,12 @@ namespace Microsoft.AspNetCore.Components.Endpoints.Forms;
internal class EndpointAntiforgeryStateProvider(IAntiforgery antiforgery) : DefaultAntiforgeryStateProvider()
{
private HttpContext? _context;
private bool _canGenerateToken;

internal void SetRequestContext(HttpContext context)
{
_context = context;
_canGenerateToken = true;
}

public override AntiforgeryRequestToken? GetAntiforgeryToken()
Expand All @@ -24,17 +26,23 @@ internal void SetRequestContext(HttpContext context)
return _currentToken;
}

// We already have a callback setup to generate the token when the response starts if needed.
// If we need the tokens before we start streaming the response, we'll generate and store them;
// otherwise we'll just retrieve them.
// In case there are no tokens available, we are going to return null and no-op.
var tokens = !_context.Response.HasStarted ? antiforgery.GetAndStoreTokens(_context) : antiforgery.GetTokens(_context);
if (tokens.RequestToken is null)
if (_currentToken == null && _canGenerateToken)
{
return null;
// We already have a callback setup to generate the token when the response starts if needed.
// If we need the tokens before we start streaming the response, we'll generate and store them;
// otherwise we'll just retrieve them.
// In case there are no tokens available, we are going to return null and no-op.
var tokens = !_context.Response.HasStarted ? antiforgery.GetAndStoreTokens(_context) : antiforgery.GetTokens(_context);
if (tokens.RequestToken is null)
{
return null;
}

_currentToken = new AntiforgeryRequestToken(tokens.RequestToken, tokens.FormFieldName);
}

_currentToken = new AntiforgeryRequestToken(tokens.RequestToken, tokens.FormFieldName);
return _currentToken;
}

internal void DisableTokenGeneration() => _canGenerateToken = false;
}
19 changes: 11 additions & 8 deletions src/Components/Endpoints/src/RazorComponentEndpointInvoker.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,9 @@
using System.Text;
using System.Text.Encodings.Web;
using Microsoft.AspNetCore.Antiforgery;
using Microsoft.AspNetCore.Components.Endpoints.Forms;
using Microsoft.AspNetCore.Components.Endpoints.Rendering;
using Microsoft.AspNetCore.Components.Forms;
using Microsoft.AspNetCore.Components.Infrastructure;
using Microsoft.AspNetCore.Diagnostics;
using Microsoft.AspNetCore.Http;
Expand Down Expand Up @@ -76,14 +78,6 @@ private async Task RenderComponentCore(HttpContext context)
return;
}

context.Response.OnStarting(() =>
{
// Generate the antiforgery tokens before we start streaming the response, as it needs
// to set the cookie header.
antiforgery!.GetAndStoreTokens(context);
return Task.CompletedTask;
});

if (httpActivityContext != default)
{
_activityLinkStore.SetActivityContext(ComponentsActivityLinkStore.Http, httpActivityContext, null);
Expand Down Expand Up @@ -143,8 +137,17 @@ await _renderer.InitializeStandardComponentServicesAsync(
var bufferingFeature = context.Features.GetRequiredFeature<IHttpResponseBodyFeature>();
bufferingFeature.DisableBuffering();

// Store the tokens if not emitted already in case we stream a form in the response.
antiforgery!.GetAndStoreTokens(context);

context.Response.Headers.ContentEncoding = "identity";
}
else if (endpoint.Metadata.GetMetadata<ConfiguredRenderModesMetadata>()?.ConfiguredRenderModes.Length == 0)
{
// Disable token generation on EndpointAntiforgeryStateProvider if we are not streaming.
var provider = (EndpointAntiforgeryStateProvider)context.RequestServices.GetRequiredService<AntiforgeryStateProvider>();
provider.DisableTokenGeneration();
}

// Importantly, we must not yield this thread (which holds exclusive access to the renderer sync context)
// in between the first call to htmlContent.WriteTo and the point where we start listening for subsequent
Expand Down
Loading