Validate the `IAntiforgeryValidationFeature` on the request before reading from the form

46 views Asked by At

I have a Blazor server web application set up using asp.net core identity, when i log in everything is fine but if i log out i get this error:

An unhandled exception occurred while processing the request. InvalidOperationException: This form is being accessed with an invalid anti-forgery token. Validate the IAntiforgeryValidationFeature on the request before reading from the form. Microsoft.AspNetCore.Http.Features.FormFeature.HandleUncheckedAntiforgeryValidationFeature()

Stack Query Cookies Headers Routing InvalidOperationException: This form is being accessed with an invalid anti-forgery token. Validate the IAntiforgeryValidationFeature on the request before reading from the form. Microsoft.AspNetCore.Http.Features.FormFeature.HandleUncheckedAntiforgeryValidationFeature() Microsoft.AspNetCore.Http.Features.FormFeature.ReadForm() lambda_method77(Closure , object , HttpContext , object ) Microsoft.AspNetCore.Http.RequestDelegateFactory+<>c__DisplayClass104_2+<b__2>d.MoveNext() Microsoft.AspNetCore.Antiforgery.Internal.AntiforgeryMiddleware.InvokeAwaited(HttpContext context) Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context) Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext context) Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddlewareImpl.Invoke(HttpContext context)

I have tried to add @Html.AntiForgeryToken() to the form although it does not recognise @Hmtml

1

There are 1 answers

0
Qing Guo On

Blazor endpoints now require antiforgery protection by default. You can enable antiforgery support using the new antiforgery middleware and using the AntiforgeryToken component to generate tokens for rendered forms. The EditForm component will add the antiforgery token automatically for you.

Add the AntiforgeryToken component like:

   <form>
        <AntiforgeryToken />
    </form>

And add

@using Microsoft.AspNetCore.Antiforgery;
@attribute [RequireAntiforgeryToken]

Besides, try to set app.UseAntiforgery() after app.UseAuthentication().

You can have a look at Blazor Antiforgery integration to know more.