ValidateAntiForgeryToken Attribute in ASP.NET MVC

Before beginning, you need some information about attacks which is a very sensible thing. A server may have a number of applications and receive a number of requests to an application, but the server can’t find which request is valid.

Really, the server doesn’t have any knowledge to find the valid request.  Isn't  it true?

The answer is absolutely yes, and it is practically proven.

I developed one sample application and ran it in the browser.

See here, the request and response are both coming from your application only.

I just tried to change request scenarios and I sent the request to controller from one third party application.

Here I made a request from one dummy html page and it got a valid response from server.


You can prevent it by using identity values with the help of the ValidateAntiForgeryToken in Asp.Net MVC.

Just add an attribute to your code.
  1. [HttpPost]  
  2. [ValidateAntiForgeryToken]  
  3. [ActionName("Index")]  
  4. public ActionResult IndexPost()  
  5. {  
  6.    string userName = Request.Form["txtUser"].ToString();  
  7.    string passWord = Request.Form["txtAddress"].ToString();  
  8.    return Json(true);  
  9. }  
  1. @Html.AntiForgeryToken()  
  2.     <p>UserName</p><input type="text" id="txtUser" name="txtUser" value="Maruthi" /><br/>  
  3.     <p>Address</p><input type="text" id="txtAddress" name="txtAddress" value="India" /><br/>  
  4.     <p></p><input type="submit" value="PostData" />  
Now let’s try again after adding ValidateAntiForgeryToken and check the output

This time you will not get any response from your server and the server can validate your request with forgery value.

How will  ValidateAntiForgeryToken work internally and how it is does it validate your request?
  • With the help of IHtmlString, a unique value created and stored  in your browser cookies.
  • Every request must carry this value (AntiForgeryToken) under Request. Form[0]
  • Internally, the Authorization filter helps to validate this token value.