Cross-Site Request Forgery In ASP.NET MVC

Here will learn what Cross- site Request forgery in ASP.NET MVC is and how to protect our ASP.NET MVC application from the CSRF.

Cross- site Request forgery is abbreviated as “CSRF”.

What is CSRF

CSRF is an attack in which a user logs in to a website like ABC.com and after login user opens other site called malicious site in another tab, then this malicious site sends request to (ABC.com) valid site using existing credential or existing session for attacking the site. Valid site( ABC.com) assumes that this coming request is a valid request or coming from a valid user, so it executes that request and site is hacked by the CSRF.

diagram

After recognizing this attack ,Microsoft provides an Attribute called “AntiForgeryToken”. It is very simple to use in our site ,just we need to add “@Html.AntiForgeryToken” in view with that we need to add this in controller also as a attribute [ValidateAntiForgeryToken] to validating this. Basically AntiForgeryToken is used in HTTPPost method.

Now we learn this with an example using ASP.NET MVC.

Go to visual studio and create a new project and select an ASP.NET MVC 4 Web Application and give the name for project ,in my case it is “CSRFInMVCApplication” after that click ok then a window will open from there select a template as “Basic” and view engine as “Rezor”.

web

basic

After clicking ok it will create a project, After that right click on model folder and add a class name “CollageInfo.cs”, and write the following code to this class,
  1. public class CollageInfo  
  2. {  
  3.     [Key]  
  4.     public int CollageID   
  5.     {  
  6.         get;  
  7.         set;  
  8.     }  
  9.     [Required(ErrorMessage = " please Enter Name")]  
  10.     public string CollageName   
  11.     {  
  12.         get;  
  13.         set;  
  14.     }  
  15.     [Required(ErrorMessage = "pleaes Enter Address")]  
  16.     public string CollageAddress   
  17.     {  
  18.         get;  
  19.         set;  
  20.     }  
  21.     [Required(ErrorMessage = "please Enter Department")]  
  22.     public string CollageDepartment   
  23.     {  
  24.         get;  
  25.         set;  
  26.     }  
  27. }  
After completion of model class we need to add a controller to this project. For that right click on the controller folder and give the name as “CollageController” with Empty MVC Controller template.

Controller

After adding controller we need to add action method name “collageInfo” with [HttpGet] and [HttpPost]. So for that write the following code in controller collageInfo action method.
  1. [HttpGet]  
  2. public ActionResult collageInfo()   
  3.     {  
  4.         return View();  
  5.     }  
  6.     [HttpPost]  
  7. public ActionResult collageInfo(CollageInfo _clgInfo)   
  8. {  
  9.     return View(_clgInfo);  
  10. }  
After adding the action method we need to add the view. For adding the view right click on the collageInfo action method and add the view like the following,

view

After clicking on add it will generate code for the view. Here's the code for view,
  1. @model CSRFInMVCApplication.Models.CollageInfo    
  2. @{    
  3.     ViewBag.Title = "collageInfo";    
  4. }    
  5.   
  6. <h2>collageInfo</h2>    
  7.     @using (Html.BeginForm()) {    
  8.     @Html.ValidationSummary(true)    
  9.   
  10. <fieldset>  
  11.     <legend>CollageInfo</legend>  
  12.     <div class="editor-label">    
  13.         @Html.LabelFor(model => model.CollageName)    
  14.     </div>  
  15.     <div class="editor-field">    
  16.         @Html.EditorFor(model => model.CollageName)    
  17.         @Html.ValidationMessageFor(model => model.CollageName)    
  18. <   /div>  
  19.     <div class="editor-label">    
  20.         @Html.LabelFor(model => model.CollageAddress)    
  21.     </div>  
  22.     <div class="editor-field">    
  23.         @Html.EditorFor(model => model.CollageAddress)    
  24.         @Html.ValidationMessageFor(model => model.CollageAddress)    
  25.     </div>  
  26.     <div class="editor-label">    
  27.         @Html.LabelFor(model => model.CollageDepartment)    
  28.     </div>  
  29.     <div class="editor-field">    
  30.         @Html.EditorFor(model => model.CollageDepartment)    
  31.         @Html.ValidationMessageFor(model => model.CollageDepartment)    
  32.     </div>  
  33.     <p>  
  34.         <input type="submit" value="Create" />  
  35.     </p>  
  36. </fieldset>    
  37. }    
  38.   
  39. <div>    
  40.     @Html.ActionLink("Back to List""Index")    
  41. </div>    
  42.     @section Scripts {    
  43.     @Scripts.Render("~/bundles/jqueryval")    
  44. }    
Now run your application, go to the following URL and see the output

http://localhost:50688/Collage/Collageinfo

output

Right click on this page and click on View Source, you will see source code of this page and save this code as

.HTML file

html

After saving this file as .HTML, now open this file (.HTML).

Code for HTML file is
  1. <html>  
  2.   
  3. <head>  
  4.     <meta charset="utf-8" />  
  5.     <meta name="viewport" content="width=device-width" />  
  6.     <title>collageInfo</title>  
  7.     <link href="/Content/site.css" rel="stylesheet" />  
  8.     <script src="/Scripts/modernizr-2.6.2.js"></script>  
  9. </head>  
  10.   
  11. <body>  
  12.     <h2>collageInfo</h2>  
  13.     <form action="http://localhost:50688/Collage/Collageinfo" method="post">  
  14.         <fieldset>  
  15.             <legend>CollageInfo</legend>  
  16.             <div class="editor-label"> <label for="CollageName">CollageName</label> </div>  
  17.             <div class="editor-field"> <input class="text-box single-line" data-val="true" data-val-required=" please Enter Name" id="CollageName" name="CollageName" type="text" value="" /> <span class="field-validation-valid" data-valmsg-for="CollageName" data-valmsg-replace="true"></span> </div>  
  18.             <div class="editor-label"> <label for="CollageAddress">CollageAddress</label> </div>  
  19.             <div class="editor-field"> <input class="text-box single-line" data-val="true" data-val-required="pleaes Enter Address" id="CollageAddress" name="CollageAddress" type="text" value="" /> <span class="field-validation-valid" data-valmsg-for="CollageAddress" data-valmsg-replace="true"></span> </div>  
  20.             <div class="editor-label"> <label for="CollageDepartment">CollageDepartment</label> </div>  
  21.             <div class="editor-field"> <input class="text-box single-line" data-val="true" data-val-required="please Enter Department" id="CollageDepartment" name="CollageDepartment" type="text" value="" /> <span class="field-validation-valid" data-valmsg-for="CollageDepartment" data-valmsg-replace="true"></span> </div>  
  22.             <p> <input type="submit" value="Create" /> </p>  
  23.         </fieldset>  
  24.     </form>  
  25.     <div> <a href="/Collage">Back to List</a> </div>  
  26.     <script src="/Scripts/jquery-1.8.2.js"></script>  
  27.     <script src="/Scripts/jquery.unobtrusive-ajax.js"></script>  
  28.     <script src="/Scripts/jquery.validate.js"></script>  
  29.     <script src="/Scripts/jquery.validate.unobtrusive.js"></script>  
  30. </body>  
  31.   
  32. </html>  
Now double click on html file and enter some data then click on “Create”, this window will be same like view.

Now enter some data and click on “Create” button .

create

Now enter some data and click on “Create” button .

create

When you click on create button, you will see that this is redirecting to action method “CollageInfo”, its called CSRF attack.

To prevent from this attack, Microsoft provide us a keyword name “@Html.AntiForgeryToken() “ For view, we have to add this keyword as shown below,

code

After this we need to add a attribute to action method attribute is [ValidateAntiForgeryToken]

code

Now if you will run your HTML file and will click on create button it will give error name is required anti-forgery form field "__RequestVerificationToken" is not present

In this way we can prevent this CSRF attack. 

Up Next
    Ebook Download
    View all
    Learn
    View all