ValidateAntiForgeryToken purpose, explanation and example

Tabriz Atayi picture Tabriz Atayi · Nov 29, 2012 · Viewed 201.7k times · Source

Could you explain ValidateAntiForgeryToken purpose and show me example about ValidateAntiForgeryToken in MVC 4?

I could not find any examples which explain this attribute?

Answer

Richard Szalay picture Richard Szalay · Nov 29, 2012

MVC's anti-forgery support writes a unique value to an HTTP-only cookie and then the same value is written to the form. When the page is submitted, an error is raised if the cookie value doesn't match the form value.

It's important to note that the feature prevents cross site request forgeries. That is, a form from another site that posts to your site in an attempt to submit hidden content using an authenticated user's credentials. The attack involves tricking the logged in user into submitting a form, or by simply programmatically triggering a form when the page loads.

The feature doesn't prevent any other type of data forgery or tampering based attacks.

To use it, decorate the action method or controller with the ValidateAntiForgeryToken attribute and place a call to @Html.AntiForgeryToken() in the forms posting to the method.