In this article, we will try to understand Anti-forgery Token in ASP.NET MVC.
Anti-forgery stands for “Act of copying or imitating things like a signature on a check, an official document to deceive the authority source for financial gains”.
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.
- Now we have created a new MVCWebapplication project by File- New Project- WebApplication MVC.
- Now add TransferAmt action method which will fetch the value of amount as amt and act as the account from Request.Form as shown below.
public ActionResult TransferAmt()
{
// Money transfer logic goes here
return Content(Request.Form["amt"] + " has been transferred to account " + Request.Form["act"]);
}
- Now, in add TransferAmt View, add the below code.
<html>
<head>
<title>Transfer money</title>
</head>
<body>
<div> Transfer
<form action="Home/TransferAmt" method="post"> Amount <input type="text" name="amount" value="" /><br /> Account No. <input type="text" name="account" value="" />
<br />
<input type="submit" value="Add Money" />
</form>
</div>
</body>
</html>
The above code has two textboxes, amt and act. Now formaction is has the action as TransferAmt.
- In Index action method, call TransferAmt View as shown below.
public ActionResult Index()
{
return View("TransferAmt");
}
- Now, you can run in Index action method to call TransferAmt View, as shown below.
- Now, enter the values and click on Add Money button.
- You will get the below result.
- Now, add another MVC project and add the below code into about View.
<div>
Win 1000000 US$ by playing ultimate game
<form action="http://localhost:64443/Home/TransferAmt" method="post">
<input type="hidden" name="amount" value="30000" />
<input type="hidden" name="account" value="5005" />
@*@Html.AntiForgeryToken()*@
<input type="submit" value="Play the ultimate game" />
</form>
</div>
- Now run the application and click on Play the ultimate game
- You will get the below result
Now you can see even we are able to access TransferAmt from another application, which is security breach.
Now to overcome this we will use Antiforgery Token with the help of @Html.AntiForgeryToken() in view and [ValidateAntiForgeryToken()] on actionmethod.
In the above case it is expecting a verification token which not getting supplied.
- Now if you will run the application and click on Add money by entering values you will get the below result.
- Now run the application and click on Play the ultimate game and you will get an error which is protecting your website from unwanted anti-forgery requests.