Asp.Net MVC Preventing Cross-site Request Forgery (csrf) Attacks with Example

  Total Views : 2253
  Comments : 1
 
  Keywords : What is cross site request forgery (csrf) in asp.net mvc, How to prevent cross site request forgery attacks in asp.net mvc, Understand cross site request forgery (csrf) in asp.net mvc

Here we will learn what is cross site request forgery (CSRF) attacks in asp.net mvc and how to protect asp.net mvc application against cross site request forgery attack.

What is Cross Site Request Forgery?

Cross Site Request Forgery is a attack in which User or Victim is already login to Valid site (XYZBANK.Com) and in same way Victim open some other Malicious site in another tab then Malicious site send request to valid site (XYZBANK.Com) using logged in session of victim for attack as (XYZBANK.Com) only know that the request which is coming from valid User and it Execute the task and Victim has been attacked using Cross Site Request Forgery.

 

Cross site request forgery attack in asp.net mvc website

 

Microsoft has recognize this threat and for preventing it has provide AntiForgeryToken. It is simple to use just add @Html.AntiForgeryToken() on View and on HttpPost of Action Method we need to add attribute to validate it [ValidateAntiForgeryToken].

 

Generally AntiForgeryToken only work for [HttpPost] Request. Now we will learn how to use AntiForgeryToken to prevent cross site request forgery by creating simple Application in Visual Studio.

Create New Asp.Net MVC Application

Let's start with creating new asp.net mvc 4 application for that Open visual studio studio à Go to File à Select New à Select Project

 

create new asp.net mvc project from visual studio 2012

 

After that you will see new dialog will pop up for selecting your Template and Project type. From Templates select Visual C# à inside that select Web and then project type select ASP.NET MVC 4 Web Application and here we are giving name as “Tutorial11” then finally click on ok button 

 

select asp.net mvc 4 web application and click ok to create new mvc application

 

After naming it just click on OK now new dialog will pop up for selecting template in that Select Basic template and select view engine as Razor then click ok like as shown below

 

select basic template to create new application in asp.net mvc

 

After click OK it will create asp.net mvc that will be like as shown below

 

Cross site request forgery attack in asp.net mvc website

Add New Model (StudentDetails) in Asp.Net MVC

Now let’s add simple Model in Model Folder with Name StudentDetails. For adding Model just right click on Model Folder and select Add à and then select Class and Name your class as StudentDetails.

 

Give name to new model class in asp.net mvc cross site request forgery

 

After creating Model StudentDetails now let's add Properties like as shown below

 

using System;

using System.Collections.Generic;

using System.ComponentModel.DataAnnotations;

using System.Linq;

using System.Web;

 

namespace Tutorial11.Models

{

public class StudentDetails

{

[Key]

public int StudentID { get; set; }

[Required (ErrorMessage="Enter Name")]

public string Name { get; set; }

[Required(ErrorMessage = "Enter Address")]

public string Address { get; set; }

[Required(ErrorMessage = "Enter Division")]

public string Division { get; set; }

}

}

After completion of model creation and add Properties now we are going to add new controller

Add New Controller in Asp.Net MVC (StudentController)

For adding controller just Right click on Controller Folder select Add à then select Controller. As you select controller a new dialog will popup Add Controller

 

create new controller in asp.net mvc cross site request forgery

 

Give name to controller as “StudentController” and in template we are not going to select any template for that we are selecting “Empty MVC controller” then click on Add Button. Once we create new controller "StudentController" that will contain code like as shown below.

 

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.Mvc;

 

namespace Tutorial11.Controllers

{

public class StudentController : Controller

{

//

// GET: /Student/

public ActionResult Index()

{

return View();

}

}

}

Now let’s add action method to student controller. We are going to add 2 action method for student controller one handling [HttpGet] Request and other for Handling [HttpPost] Request.

 

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.Mvc;

using Tutorial11.Models;

 

namespace Tutorial11.Controllers

{

public class StudentController : Controller

{

 

[HttpGet]

public ActionResult StudentInfo()

{

return View();

}

[HttpPost]

public ActionResult StudentInfo(StudentDetails objSD)

{

return View(objSD);

}

}

}

Adding View in Asp.Net MVC (StudentInfo)

After adding Action Method now let’s Add View (StudentInfo). For adding view just Right click anywhere inside Action Method and select Add view a New Dialog will popup Add View.

 

Add new view in asp.net mvc cross site request forgery application

 

Now the name of view will be similar to name of action method we are not going to change it and View Engine will be set to Razor.  We are going to create a strongly-Typed view hence we are going to check this option and select your Model which we have created StudentDetails if you are not finding your Model just build your Application and then retry this process of Adding Strongly-Typed view. After that we are going to use Scaffold Template for that we selected Create template and finally click on Add button to add view.

 

After Adding it will create a Folder inside Views with same name as Controller Name Student and inside that it will Add view (StudentInfo).

 

After adding view in asp.net mvc application our project structure

 

After adding StudentInfo view following is the code snippet of StudentInfo view which is generated.

 

@model Tutorial11.Models.StudentDetails

@{

ViewBag.Title = "StudentInfo";

}

<h2>StudentInfo</h2>

@using (Html.BeginForm()) {

@Html.ValidationSummary(true)

 

<fieldset>

<legend>StudentDetails</legend>

<div class="editor-label">

@Html.LabelFor(model => model.Name)

</div>

<div class="editor-field">

@Html.EditorFor(model => model.Name)

@Html.ValidationMessageFor(model => model.Name)

</div>

<div class="editor-label">

@Html.LabelFor(model => model.Address)

</div>

<divclass="editor-field">

@Html.EditorFor(model => model.Address)

@Html.ValidationMessageFor(model => model.Address)

</div>

<div class="editor-label">

@Html.LabelFor(model => model.Division)

</div>

<div class="editor-field">

@Html.EditorFor(model => model.Division)

@Html.ValidationMessageFor(model => model.Division)

</div>

<p>

<input type="submit" value="Create"/>

</p>

</fieldset>

}

<div>

@Html.ActionLink("Back to List", "Index")

</div>

@section Scripts {

@Scripts.Render("~/bundles/jqueryval")

}

Now save your application and Run.

 

Add student information details in asp.net mvc cross site request forgery application

 

Now we will learn how cross site request forgery attack will occured on website in asp.net mvc. We created view and it is rendered in browser now just right click on view and select view page source that will be like as shown below.

 

page source of student view page in asp.net mvc cross site request forgery

 

 Now copy this Html and save in text file and name File as a.html like as shown below.

 

 

Now open this file as Txt and find line [<form action="/Student/StudentInfo" method="post">] and change this with URL which is rendered in Browser [<form action="http://localhost:8356/Student/StudentInfo" method="post">] finally save this file and now double click and open this file in browser. If you check that file is same as our original view.

 

Open saved file in asp.net mvc cross site request forgery

 

Now just enter some data and click on create button after that you will see Magic. Ohhh we have posted a.html file and Action Method StudentInfo got called with all values. This is how attack can create for any application which is not secured.

 

Debug view of cross site request forgery in asp.net mvc application

Adding @Html.AntiForgeryToken() to Studentinfo view

For Preventing this attack we need to add @Html.AntiForgeryToken()  to StudentInfo View like as shown below.

 

Adding AntiForgeryToken in html page in asp.net mvc

 

Now on [HttpPost] of ActionMethod we need to add [ValidateAntiForgeryToken]. Following is the way we need to add ValidateAntiForgeryToken to Studentinfo [HttpPost] Action Method.

 

Adding ValidateAntiForgeryToken to Studentinfo [HttpPost] Action Method in asp.net mvc cross site request forgery

 

 Now save application and Run. If we are going to access our StudentInfo (http://localhost:8356/Student/StudentInfo) page from browser then it will work properly as you can see below.

 

Output of student info page to avoid cross site request forgery in asp.net mvc

 

Now if we try to open a.html page for posting data then it will fire Error like (required anti-forgery form field "__RequestVerificationToken" is not present.).

 

Error for cross site request forgery attack in asp.net mvc website

This is how we can protect our application against Cross Site Request Forgery in asp.net mvc. Let’s check what actually happen beyond the seen.

 

When we add @Html.AntiForgeryToken() to a view it add unique value in form of Hidden Field and also a session Cookie. To view hidden field  just view source of StudentInfo view. Following is the hidden field in HTML which is generated.

 

<!-- Rendered HTML in the client browser -->

<input name="__RequestVerificationToken" type="hidden" value="vw4vaP7U2oQR7zWonY6JQHVPJ1vddp9qmUAJ2rTMbriexw54Eb5RcmzLmK9hsx2aPZD9WYkhgf9LKU3KXkehbK-DxlzZWs3wJQ7saMdy6nyZWvvD8CxS2bYHu-3iiIkyFkq9FLbJKcjwolrou-nCYsQ_vyL0VvIu2vsioTgZ12c1" />

Following is the session which is created when we add AntiForgeryToken() to avoid cross site request forgery in asp.net mvc.

 

Session which is created for AntiForgeryToken in cross site request forgery in asp.net mvc

 

When we post StudentInfo form then ASP.NET MVC framework checks for a request forgery and also it check for  __RequestVerificationToken Hidden field and __RequestVerificationToken Cookie are present or not. If either the cookie or the form field values are missing, or the values don't match, ASP.NET MVC does not process the action. This his how we can prevent cross site request forgery attack in asp.net mvc.

 Comments (1)

  • Anjani Pandey tutlane registered profile image
     
    Anjani Pandey   Reply

    Nice One :))

     Feb 09, 2016

Leave a comment

  • Default Tutlane User