Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Disable request verification token in ASP.NET Core

ASP.NET Core MVC seems to inject a request verification token in all of my forms:

<form class="actions" method="post">
    <input type="submit" class="btn btn-primary" value="Yes">
    <a class="btn btn-secondary" href="/some/url">No</a>
    <input name="__RequestVerificationToken" type="hidden" value="...">
</form>

I'm handling CSRF in Ajax and don't want this extra input element in all of my forms. Any way to disable it?

The element is added even without a call to AddAntiforgery in Startup.cs. I'm running on ASP.NET Core 3.1.

like image 391
ThomasArdal Avatar asked Jan 25 '26 12:01

ThomasArdal


2 Answers

Antiforgery middleware is added to the Dependency injection container when one of the following APIs is called in Startup.ConfigureServices:

AddMvc
MapRazorPages
MapControllerRoute
MapBlazorHub

Details please check this document

To disable it, try below IgnoreAntiforgeryToken attribute

[Authorize]
[AutoValidateAntiforgeryToken]
public class ManageController : Controller
{
    [HttpPost]
    [IgnoreAntiforgeryToken]
    public async Task<IActionResult> DoSomethingSafe(SomeViewModel model)
    {
        // no antiforgery token required
    }
}

Details can be found here

like image 145
Elendil Zheng-MSFT Avatar answered Jan 27 '26 05:01

Elendil Zheng-MSFT


The token is appended by the Form Tag Helper. If you don't need the other features of the Tag Helper, it can be removed using @removeTagHelper (in view or globally by adding to _ViewImports.cshtml):

@removeTagHelper Microsoft.AspNetCore.Mvc.TagHelpers.FormTagHelper, Microsoft.AspNetCore.Mvc.TagHelpers

See ASP.NET Core documentation for further details/options.

like image 29
mcNux Avatar answered Jan 27 '26 05:01

mcNux



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!