Prevent Cross-Site Request Forgery (CSRF) using ASP.NET anti-forgery token

The anti-forgery token used to help protect your application against cross-site request forgery. To use this feature, call the AntiForgeryToken method from a form and add the ValidateAntiForgeryTokenAttribute attribute to the action method that you want to protect. It generates a hidden  field (anti-forgery token) that is validated when the form is submitted.

To generate the AntiForgeryToken and the Cookie on the client side, we declare it as follows in the HTML form in the user.cshtml

@using (Html.BeginForm()) {
@Html.ValidationSummary(true)
@Html.AntiForgeryToken()
<fieldset>
<legend>UserDetails</legend>

This ensures that a form being posted to the server was actually generated by the same server. Thus fake forms that do not have the AntiForgeryToken from the correct server, gets rejected.

To validate an incoming post request, add the [ValidateAntiForgeryToken] filter to your target action method.

[ValidateAntiForgeryToken]
public ViewResult SubmitUpdate()
{
// Your code goes here…
}

Assuming that everything is going well, the request goes through as normal. But if not, there’s an authorization failure with message  “A required anti-forgery token was not supplied or was invalid”.

In case you want to protect multiple forms in your application independently of each other, you can use a “salt” value when you call Html.AntiForgeryToken()…

HTML Code:

<%= Html.AntiForgeryToken(“someString”) %>

Controller Code:

[ValidateAntiForgeryToken(Salt=”someString”)]
public ViewResult SubmitUpdate()
{
// Your code goes here…
}

Salt can be any non empty string.

A different salt value means a different anti-forgery token will be generated.

In conclusion, ASP.NET MVC’s AntiForgeryToken helpers are easy to use, and work very nicely!

Thank you!

Happy Coding 🙂

asp.net mvc
asp.net mvc
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s