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?
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()afterapp.UseAuthentication()middleware to avoid this kind of issue.More details, you could refer to below codes:
Result: