Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AntiforgeryToken not generating __RequestVerificationToken hidden field Blazor Server

I have an app built using .NET8 Blazor with InteractiveServerRenderMode.

App.razor is configured like in Template you get when you create Blazor Server App with Global Interactivity and Identity.

I have one Toolbar component where I am trying to add SignOut Functionality with following form

<AuthorizeView>
<Authorized>
<form action="Account/Logout" method="post">
    <AntiforgeryToken />
    <input type="hidden" name="ReturnUrl" value="@currentUrl" />
   <button type="submit">Sign out</button>
</form>
</Authorized>
</AuthorizeView>

But when I submit this form with Sign out button I get following error

BadHttpRequestException: Invalid anti-forgery token found when reading parameter "string returnUrl" from the request body as form.

This error is right as when I inspect element I don't see __RequestVerificationToken field. It is not beind rendered I even tried to use @attribute [RequireAntiforgeryToken] but it is still not working.

I also tried to register it in Program.cs as

var app = builder.Build();
if (app.Environment.IsDevelopment())
    app.UseMigrationsEndPoint();
else
{
    app.UseExceptionHandler("/Error", createScopeForErrors: true);
    app.UseHsts();
}

app.UseHttpsRedirection();
app.UseStaticFiles();
//app.UseAuthentication();
//app.UseAuthorization();
app.UseAntiforgery();
app.MapRazorComponents<App>().AddInteractiveServerRenderMode();
app.MapAdditionalIdentityEndpoints();
app.Run();

Anyone who can point what I am doing wrong here?

like image 364
Alisbha Khan Avatar asked Apr 28 '26 17:04

Alisbha Khan


1 Answers

BadHttpRequestException: Invalid anti-forgery token found when reading parameter "string returnUrl" from the request body as form.

According to the error message, you should make sure you have put the app.UseAntiforgery(); middleware with the right order inside the program.cs.

Please note, according to this github issue, you need also put app.UseAntiforgery() after app.UseAuthentication() middleware to avoid this kind of issue.

More details, you could refer to below codes:

...
var app = builder.Build();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseMigrationsEndPoint();
}
else
{
    app.UseExceptionHandler("/Error", createScopeForErrors: true);
    // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
    app.UseHsts();
}

app.UseHttpsRedirection();

app.UseStaticFiles();
app.UseAntiforgery();

app.MapRazorComponents<App>()
    .AddInteractiveServerRenderMode();

// Add additional endpoints required by the Identity /Account Razor components.
app.MapAdditionalIdentityEndpoints();

app.Run();

Result:

enter image description here

like image 78
Brando Zhang Avatar answered May 05 '26 04:05

Brando Zhang