350

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

I could not find any examples which explain this attribute?

Mikhail
  • 9,186
  • 4
  • 33
  • 49
Tabriz Atayi
  • 5,880
  • 7
  • 28
  • 33
  • 9
    Check this post http://prideparrot.com/blog/archive/2012/7/securing_all_forms_using_antiforgerytoken – VJAI Nov 29 '12 at 09:21
  • 1
    By the way, I really don't understand why MS haven't made it possible to put this right inside the `.BeginForm` helper. So this thing is there automatically, like in Rails – jazzcat Apr 16 '17 at 16:29

3 Answers3

387

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.

Richard Szalay
  • 83,269
  • 19
  • 178
  • 237
  • 1
    Judging by the way MVC CRUD Templates implement this, this does not appear to be correct. If you look at the forms using it that it generates, you'll see: @Html.AntiForgeryToken() inside each form. The VSDoc for this says it generates a hidden form field with the anti-forgery token in it. It seems clear it's actually a hidden form field, and not a cookie. Is there a separate scenario where it is a cookie? – Chris Moschini Apr 18 '13 at 18:04
  • 6
    @Chris It's both. As per my answer: "writes a unique value to an HTTP-only cookie and then *the same value is written to the form*" – Richard Szalay Apr 18 '13 at 21:39
  • 1
    Ah, missed that detail. You are correct - AntiForgeryToken article: http://blog.stevensanderson.com/2008/09/01/prevent-cross-site-request-forgery-csrf-using-aspnet-mvcs-antiforgerytoken-helper/ – Chris Moschini Apr 18 '13 at 22:20
  • 28
    Why isn't this set by default? – Christian Hagelid May 23 '13 at 00:20
  • Documentation links would be nice! – TheOptimusPrimus Jul 31 '13 at 16:46
  • 2
    @TheOptimusPrimus The reference to the class name in the last paragraph links to the MSDN docs. – Richard Szalay Sep 04 '13 at 10:46
  • 14
    @Christian because it is not Ruby on Rails. ;-) – Martin Capodici Jan 26 '14 at 21:07
  • 1
    @Martin Capodici i'd say not every web-site needs this kind of validation which costs some additional processing. – Jan Lobau Sep 07 '14 at 13:07
  • 7
    It seems that the form __RequestVerificationToken and cookie __RequestVerificationToken are not the same, they work as a pair. – WaiKit Kung Apr 08 '15 at 15:54
  • I got a question: And in which cases should I use that key? – Ivan Sieder Jan 26 '16 at 20:37
  • so would it be fair to say that if your site doesnt allow CORS then theres no benefit from the anti forgery token? – rdans Jun 14 '17 at 10:46
  • 6
    @rdans Not at all, CORS and CSRF are entirely different. CORS is for allowing other domains to access APIs on your server, CSRF is about making sure that a form post came from the page you expected it to. – Richard Szalay Jun 14 '17 at 11:56
  • 1
    Further to my previous comment: CORS is only enforced on cross-origin `XMLHttpRequest` and `fetch` requests. Form posts, images, and script/css are all excluded from CORS and thus can be used to exploit your existing cookies on another domain. – Richard Szalay Jan 25 '18 at 02:54
  • 8
    In .NET Core It is possible to configure so that all requests would validate anti forgery token by default by adding a global filter `services.AddMvc(options => { options.Filters.Add(new AutoValidateAntiforgeryTokenAttribute()); });` – solo Aug 07 '20 at 05:55
61

The basic purpose of ValidateAntiForgeryToken attribute is to prevent cross-site request forgery attacks.

A cross-site request forgery is an attack in which a harmful script element, malicious command, or code is sent from the browser of a trusted user. For more information on this please visit http://www.asp.net/mvc/overview/security/xsrfcsrf-prevention-in-aspnet-mvc-and-web-pages.

It is simple to use, you need to decorate method with ValidateAntiForgeryToken attribute as below:

[HttpPost]  
[ValidateAntiForgeryToken]  
public ActionResult CreateProduct(Product product)  
{
  if (ModelState.IsValid)  
  {
    //your logic 
  }
  return View(ModelName);
}

It is derived from System.Web.Mvc namespace.

And in your view, add this code to add the token so it is used to validate the form upon submission.

@Html.AntiForgeryToken()
Chandra Malla
  • 2,399
  • 22
  • 12
  • Yes you are right,you need to call @Html.AntiForgeryToken() from your form and add the ValidateAntiForgeryTokenAttribute to the action method that you want to protect. – Chandra Malla Jan 11 '15 at 16:24
19

In ASP.Net Core anti forgery token is automatically added to forms, so you don't need to add @Html.AntiForgeryToken() if you use razor form element or if you use IHtmlHelper.BeginForm and if the form's method isn't GET.

It will generate input element for your form similar to this:

<input name="__RequestVerificationToken" type="hidden" 
       value="CfDJ8HSQ_cdnkvBPo-jales205VCq9ISkg9BilG0VXAiNm3Fl5Lyu_JGpQDA4_CLNvty28w43AL8zjeR86fNALdsR3queTfAogif9ut-Zd-fwo8SAYuT0wmZ5eZUYClvpLfYm4LLIVy6VllbD54UxJ8W6FA">

And when user submits form this token is verified on server side if validation is enabled.

[ValidateAntiForgeryToken] attribute can be used against actions. Requests made to actions that have this filter applied are blocked unless the request includes a valid antiforgery token.

[AutoValidateAntiforgeryToken] attribute can be used against controllers. This attribute works identically to the ValidateAntiForgeryToken attribute, except that it doesn't require tokens for requests made using the following HTTP methods: GET HEAD OPTIONS TRACE

Additional information: learn.microsoft.com/aspnet/core/security/anti-request-forgery

Hille
  • 2,123
  • 22
  • 39
Siarhei Kavaleuski
  • 1,450
  • 14
  • 15