Skip to main content

Disable Anti-forgery token validation globally in ASP.NET Core Razor pages

In this short post, find the code to disable Anti-forgery token validation globally in ASP.NET Core Razor pages. If you are new to Razor Pages, It’s a new feature of ASP.NET Core that makes coding page-focused scenarios easier and more productive. Razor pages use handler methods to deal with the incoming HTTP request (GET/POST/PUT/Delete).

Razor Pages are designed to be automatically protected from cross-site request forgery (CSRF/XSRF) attacks. Anti-forgery token generation and validation is automatically included in Razor Pages. However, in some cases you may want to disable it. To disable anti-forgery token validation globally in Razor pages, include following code in Startup class’s ConfigureServices() method.

    o.Conventions.ConfigureFilter(new IgnoreAntiforgeryTokenAttribute());

This will turn off the anti-forgery token validation for the whole application. Please note, disabling the anti-forgery token validation does not prevent the generation of the hidden field or the cookie. It just skips the verification process.

If you wish to disable the validation only for specific methods or page models, then decorate with [IgnoreAntiforgeryToken(Order = 1001)]. The value of the order parameter is the key here to disable the token validation. The reason is, the ValidateAntiForgeryToken attribute (applied by default) has an order of 1000, therefore the IgnoreAntiforgeryToken attribute needs to have a higher order number.

Thank you for reading. Keep visiting this blog and share this in your network. Please put your thoughts and feedback in the comments section.

PS: If you found this content valuable and want to return the favour, then Buy Me A Coffee

3 thoughts on “Disable Anti-forgery token validation globally in ASP.NET Core Razor pages

  1. This is no longer correct and does not work. The current solution is to put [IgnoreAntiforgeryToken(Order = 1001)] on top of models that want to disable Anti-forgery for

Leave a Reply

Your email address will not be published. Required fields are marked *