How To Secure Your Request With AntiForgeryToken

Today we’ll discuss about AntiForgeryTokens. This article is the next part of my Registration Form With ASP.NET MVC, so if you’ve the prior knowledge of CRUD operations or how we post the form to the post action then you can go ahead with this article. But if you’ve not prior knowledge then you should read my Registration Form article first and then come back here.

Today, we’ll discuss about AntiForgeryTokens. This article is the next part of my Registration Form With ASP.NET MVC, so if you’ve any prior knowledge of CRUD operations or how we post the form to the post action, then you can go ahead with this article. But if you don't have prior knowledge, then you should read my Registration Form article first and then come back here.

Now, first of all, remove the ValidateAntiForgeryToken attribute from Create post action and @Html.AntiForgeryToken() from Create View. We’ll take our experiment just in Create module.

 

As we’ve already removed the attributes and HTML helper from the View, now this form has the security hole inside.

 

Here, we can see everything in the request. Now imagine the user who’s responsible for creating the Student record leaves the application without signing out. So this user has an active session on the server. And he is still authenticated for a few minutes, the default setting is around 20 minutes but, of course, it can vary from one application to another.

Now just imagine, I’m a hacker and I trick this user to visit the malicious page I’ve created. On this page, I’ve placed an image or iframe and a little bit of Javascript behind it. So when the page is loaded, it will send the HTTP post request to the application. Now think what can happen, because this user has an active session on the website. This request will be successfully executed on this behalf. We called this kind of attack is CSRF (Cross-Site Request Forgery). So the hacker forgery the request on a different website. Hacker can create false records in the database. He can delete all the records and tables from the database. He can attack the banking applications and the hacker just wants one security hole to enter into the system.

And a more interesting thing is, if you see the request logs you’ll know that all the request comes from the user's browsers and these requests are all valid. We won’t have any records of the hacker, like his IP Address, location etc.

So How Do We Prevent This?

We need to make sure that this request comes from the customer's browser, not from a different website. So there are 2 steps we need to follow.

  • Use Html Helper
    @Html.AntiForgeryToken() in the forms in views

    This method will create the token which is like the secret code and then put it in as a hidden field in the form and also as the cookie on user’s computer. Now let’s see this cookie in action.


    It is called request verification token. Look at the value --  it is the long weird string. This value is also stored on the user’s computer as a cookie in an encrypted format. So we can see this cookie in the browser as well.

So we give the user a token and when he posted the form, we get these two values.

  • Hidden Fields
  • Encrypted Cookie

And compare that, if they match that means it is the legitimate request otherwise it’s an attack. Because if the attacker redirects the user to the malicious page, they don’t have access to the hidden fields of the form. Because these hidden fields only exist when the user actually visits our Student form.

Even if the hacker steals the cookie, he still doesn’t have access to the hidden fields. So on the server, we do this validation if these values don’t match, it’s an attack and we immediately stop the request.

  • Now to perform the validation, we decorate our action with [ValidateAntiForgeryToken] attribute. So all the complexity of generating the token encrypting it validating it is done by MVC Framework, we don’t have to worry about it. We just have to remember to apply these attributes to our action and use the HTML helper method in post forms views.
    1. [HttpPost]  
    2. [ValidateAntiForgeryToken]  
    3. public ActionResult Create([Bind(Include = "Id,Name,Email,RetypeEmail,Phone,Cnic,Age,City,Address,DateOfBirth")] Student student) {  
    4.     if (ModelState.IsValid) {  
    5.         db.Students.Add(student);  
    6.         db.SaveChanges();  
    7.         return RedirectToAction("Index");  
    8.     }  
    9.     return View(student);  
    10. }  

Now build the application and test again. Let’s suppose we want to test again our application. Fill the form with data and remove the token from the views and submit the request.

Now if he submits the form, then the error will pop up. And this is how this item works.

 

And this is how we prevent from CSRF or XSRF attack.

Conclusion

Today, we’ve discussed how to use AntiForgeryToken and how it is helpful, and how it works under the hood. And we learned the lesson that if you’re developing online banking, transaction system, then you need to keep in mind some important tips and tricks of ASP.NET MVC to make the application more robust and secure.