Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ValidateAntiForgeryToken purpose, explanation and example

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

I could not find any examples which explain this attribute?

like image 541
Tabriz Atayi Avatar asked Nov 29 '12 08:11

Tabriz Atayi


People also ask

What is ValidateAntiForgeryToken in asp net core?

June 09, 2020. AntiForgeryToken is a security token generated by the . Net Core web application, which is used to validate a post request to guard against Cross-Site Request.

How do anti-forgery tokens work?

Now, in the case of web applications, it is termed as CSRF. CSRF is a method of attacking website where attackers imitate a trusted source sending the data to the site. [Here attacker acts like a trusted source and sends data to site and website processes the data by trusting the request.] Now, let's take an example.


2 Answers

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.

like image 157
Richard Szalay Avatar answered Oct 08 '22 07:10

Richard Szalay


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() 
like image 41
Chandra Malla Avatar answered Oct 08 '22 05:10

Chandra Malla