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.
services.AddMvc().AddRazorPagesOptions(o=> { 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.
Maybe the following will help someone.
I had an issue with cookies. On local env. cookies set fine, but when I ran my app in docker container, my authorization cookies didn’t set at all.
The reason was with cookies` settings. When configuring your services, at Startup.cs file, you have to set cookie options “isEssential” to true, so app will know, that cookies are required for your app`s normal workflow.
I used this approach on non-production app, with asp.net core mvc 3.1.
I want to note that this only worked for me when I put it on the PageModel, NOT the Action.
Yes, that’s right.
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