Cross-site request forgery, XSRF/CSRF

Cross-Site Request Forgery in ASP.NET Core FormTagHelper

Cross-Site Request Forgery is an attack to plot the user to execute an undesirable action in the web application where they have logged in. It is also called CSRF or XSRF. In this article, let us see how the ASP.NET Core prevents Cross-Site Request Forgery.

The FormTagHelper element in ASP.NET Core generates an anti-forgery token in the web application. If the <form> tag contains method=”post” attribute, it will create an anti-forgery token or request verification token.

For example, the below form tag creates an input anti-forgery token element while running.

<form  method=”post”>

The following is a screenshot of the generated anti-forgery token. It’s creating a hidden input element with a name _RequestVerificationToken.

anti-forgery token

How It Works

When the client requests an HTML form page that contains the form, the server sends the form with two tokens. One is a cookie token another one is a hidden form field. The tokens are generated randomly. So no one can guess the token value. At the time of form submission, it sends both the tokens back to the server. The server will check both tokens, if it matches with the token generated by the server, it will allow the process or transaction to happen otherwise it will forbid the request.

How to Avoid anti-forgery token

Anti-forgery taken may not be applicable in all scenarios. If you want to avoid the automatic anti-forgery token generation, use the asp-antiforgery=flase attribute in the form element that will disable the automatic anti-forgery token generation.

For example:

<form  method=”post” asp-antiforgery =”false”>

The TagHelper form element only generates the anti-forgery token. So, if the form element can opt-out by Tag Helper ‘!’ opt-out symbol. The following HTML element has ‘!’ the opt-out symbol in the form tag. So the tag will act like a normal HTML. So it will never generate the anti-forgery token. The visual studio will differentiate the HTML and TagHelper by font color. The TagHelper tag font color is a bold purple (Visual Studio “Blue” or “Light” color theme). When it is opt-out, the tag will display the default element color.

<!form  method=”post”>
</!form >

Also, we can avoid the Tag helper for the razor page using the following code:

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

From the above brief article, you can get knowledge about how the FormTagHelper prevents cross-site forgery and how to opt-out the anti-forgery token.

If you have questions, please leave your comments.

Leave a Reply

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