SharePoint Pals
 | Sign In
How to protect Application from Cross Site Request Forgery Attacks in MVC
by Tarun Kumar Chatterjee 16 May 2016
Author
.Net – Technology Specialist
Visits   
Today  :   4     Total  :    3510

All web application platforms are potentially vulnerable to CSRF (Cross-Site Request Forgery) attacks. The best way to prevent this attack in MVC application is to use Anti-Forgery token.

Consider a website "www.test1.com" contains an action method DeleteUser in User Controller. When a web request comes from a client, the controller fetches the user id from session and deletes the user from database. Consider one hacker created a site "www.test2.com" and it contains one button 'Latest Deals'. The button click event calls the "www.test1.com/User/DeleteAccount". A user is logged in "www.test1.com" and he is visiting "www.test2.com" using the same browser with another tab. When he clicking the 'Latest Deals' button, his account will delete from the test1 database. To avoid these types of unwanted requests from other sites, MVC application developers use Anti-Forgery Token.

Anti-Forgery Token is mainly used in form POST actions to verify the source of the POST data. In this method, for each page request, the web server sends a cookie to the client browser. While posting the data or next request time, the web server uses this cookie for client authentication. If the request is coming from an unauthorized site, the cookie will be null or invalid. By adding [ValidateAntiForgeryToken] above the controller and @Html.AntiForgeryToken() in the view page, we can prevent cross site requests forgery.

In the HomeController an action method

 [HttpPost]
         public ActionResult Delete(int id, Employee emp)
         {
             try
             {                
                 db.DeleteEmployee(id);                
                 return RedirectToAction("Index");
             }
             catch
             {
                 return View();
             }
         }
 This is my view code 
 @model EntityFrameworkDemo.Models.Employee
 
 @{
     ViewBag.Title = "Delete";
 }
 
 <h2>Delete</h2>
 <h3>Are you sure you want to delete this?</h3>
 <fieldset>
     <legend>Employee</legend>
 
     <div class="display-label">Name</div>
     <div class="display-field">@Model.Name</div>
 
     <div class="display-label">Address</div>
     <div class="display-field">@Model.Address</div>
 </fieldset>
 @using (Html.BeginForm()) {
     <p>
         <input type="submit" value="Delete" /> |
         @Html.ActionLink("Back to List", "Index")
     </p>
 }
 
 
 Created a test HTML having the following code:  
 <h2>Test Delete HTML</h2>
 <h3>Are you sure you want to delete this?</h3>
 <fieldset>
     <legend>Employee</legend>
 
     <div class="display-label">Name</div>
     <div class="display-field">Tarun4</div>
 
     <div class="display-label">Address</div>
     <div class="display-field">Kolkata4</div>
 </fieldset>
 <form action="http://localhost:56445/home/delete/4" method="post">    <p>
          
         <input type="submit" value="Delete" /> |
         
     </p>
 </form>
 

First run the application and then open Test.html, clicking on Delete will call HomeController Delete method and delete the data

clip_image002

To resolve the issue, define [ValidateAntiForgeryToken] on top of controller method

 [HttpPost]
         [ValidateAntiForgeryToken] 
         public ActionResult Delete(int id, Employee emp)
         {
             try
             {                
                 db.DeleteEmployee(id);                
                 return RedirectToAction("Index");
             }
             catch
             {
                 return View();
             }
 
         }
 
 

Not defining @Html.AntiForgeryToken()in views it will give you the below error

clip_image004

To resolve the error in the view, we need to change the following:

 @using (Html.BeginForm()) {
     <p>
          @Html.AntiForgeryToken()
         <input type="submit" value="Delete" /> |
         @Html.ActionLink("Back to List", "Index")
     </p>
 }
 

Now rebuild the solution and run

Then run Test.html & click on Delete button it will throw below error

clip_image006

Happy Coding

Tarun Kumar Chatterjee

blog comments powered by Disqus

SharePoint Pals

Pals
SharePoint Pals, a community portal for SharePoint developers, Administrators and End Users. Let's join hands and share the point together.
Read this on mobile

Training

Angular Js Training In Chennai
Advanced Angular Js training with real world developer scenarios
Angular Js, Web Api and Ionic for .Net Developers
All in one client side application development for .Net developers
Angular Js For SharePoint Developers
Get ready for the future. Its no more just C#

Get Connected

SharePoint Resources

SharePoint 2013 and 2010 Web Parts
Free Web Parts with Source Code for SharePoint Community




SharePoint 2013 Books and Tutorials
Collection of free SharePoint 2013 books and tutorials (eBooks, pdfs)

Supported By

Contribute your article and be eligible for a one month Free Subscription for Plural Sight. The Author of the most popular New Article (published in the previous month) will be awarded with a Free One month Plural Sight Subscription. Article can be sent to articles@sharepointpals.com in a word document.

Related Resources

Recent Tweets

Twitter January 15, 00:25
How To Enable Target Value And Actual Value In #D3 Gauge Chart https://t.co/VxSi4QnNrC

Twitter January 15, 00:24
How To Open #SharePoint List Hyperlink Column In Modal #Popup Window https://t.co/EQ7HkoZDkX

Twitter January 15, 00:24
Quick Introduction To #Asp.NetCore And It’s Features https://t.co/zAXObHCFpH

Twitter January 15, 00:22
How To Configure #PerformancePoint Services To Use Secure Store In #SharePoint 2013 https://t.co/LEwnUoI7EY

Twitter January 15, 00:21
How To Block Or Disable #Office365 Services https://t.co/Yvp2VPFIRP

Follow us @SharePointPals
Note: For Customization and Configuration, CheckOutRecent Tweets Documentation