Preventing Cross-site request forgery in ASP.NET MVC


Let us start with the problem called as XSRF (Cross-site request forgery). Later we will use the solutions and one specific to ASP.NET MVC.

XSRF: Lets assume you have an account with website example.com which uses cookie-based authentication. Following are the steps which shows how XSRF can be exploited:

  • When logging into this website, cookies are set in your browser by example.com which will be used for authentication. 
  • Somehow, you click on a link provided by hacker say, hacker.com. This page contains a form which submits any critical data to example.com. Now, your cookies will be sent along with it for authentication.
That's it, now hacker can change your recovery email address, password etc to hack your account

General Solutions:

  • Example.com should check the referral webpage link in the post request to check if the request is coming from same domain only. But this is not 100% safe as this can be spoofed.
  • Maintain a GUID as cookie and a hidden input field in form. Example.com will proceed with entertaining the request only if both have same value. 
Consider the example of forgery above in case of solution 2. Now, the GUID value as cookie will be sent in request from hacker.com by the browser. (Note that hacker.com can not read cross-domain cookies.) But that GUID value will not be a part of form. Hence, example.com will not serve the request.

Solution for ASP.NET MVC:
Use Html.AntiForgeryToken(). This sets a cookie with key __RequestVerificationToken and generates following HTML code:
<input name="__RequestVerificationToken" type="hidden" value="TdsFsfkdNddddzdfNh4YbZjmEG0sdqlUddqddiab/dfVgdd2swweFrVyeylvzuwR" />


No comments:

Post a Comment