Search code examples
c#asp.net-mvcrazorcsrf

Razor and Antiforgery


I recently came across the following note on the Microsoft documents (https://learn.microsoft.com/en-us/aspnet/core/security/anti-request-forgery):

Razor Pages are automatically protected from XSRF/CSRF. You don't have to write any additional code. See XSRF/CSRF and Razor Pages for more information.

Pointing to this other page (https://learn.microsoft.com/en-us/aspnet/core/mvc/razor-pages/index?tabs=visual-studio#xsrf) where it says:

You don't have to write any code for antiforgery validation. Antiforgery token generation and validation are automatically included in Razor Pages.

I use Razor with my ASP.NET MVC application and also protect my forms with the AntiForgeryToken helpers. Because of the way the Antiforgery tokens are validated against each other (hidden field + cookie), my users must allow cookies on the website.

I am now confused with what I read in the doc, as it seems to say that I don't need to use the @Html.AntiForgeryToken() helper or the [ValidateAntiForgeryToken] attribute when using Razor...?

As an additional question, is there a way to protect my site against CSRF attack without using the cookies?


Solution

  • Reading the first link in the post (https://learn.microsoft.com/en-us/aspnet/core/security/anti-request-forgery) I've found the explanation:

    ASP.NET Core implements anti-request-forgery using the ASP.NET Core data protection stack.

    In ASP.NET Core MVC 2.0 the FormTagHelper injects anti-forgery tokens for HTML form elements.

    For older versions of ASP.NET MVC, the helpers you mention are needed.