AntiForgeryToken in MVC Framework

March 27, 2018 0 Comments A+ a-

ASP .Net

AntiForgeryToken

  • AntiForgeryToken is a great feature in ASP.NET MVC framework.
  • It generates a hidden field in form and valid value in cookies that is validated when the form is submitted to server.
  • It protect your application against cross site request forgery.

What is Cross Site Request Forgery?

  • Cross Site Request Forgery is a one type of attack.
  • It defined as a forgery request or fraud request, which comes on an authenticated site from cross site and is treated as an authenticated request.
  • The impact of CSRF attack is limited of the capabilities exposed by the vulnerable application.
Some example of CSRF attack.
Transfer of Funds, Changing a Password etc.

You can read more about CSRF on the OWASP site.

CSRF Exmaple :
You are using inter net banking for fund transfer to other account.
A hacker knows that you are logged and URL of the money transfer submission.
Sametime You get a advertisement like click me we will get some offer. By mistake you click on that advertisement.
Then after a minute, you get message that some amount has been deducted from your accoun.
Please see the below code, What is code inside advertisement ?
   

Win IPhone

Microsoft provides us built-in functionality for avoiding this situation.
We can use that functionality in our application for security purposes.

AntiForgeryToken

  • AntiForgeryToken also called request verification tokens.
  • It prevent CSRF attacks.
  • The client requests an HTML form.
  • The server receives two token in the response. one token is sent as a cookie and other in an hidden form field.
  • The tokens are generated randomly and cannot guess the values.
While the client sub the form, Both tokens value sends to the server.
If a request does not include both tokens and same value then the server disallows the request.
Let's the below example, How does AntiForgeryToken work in MVC application ?
Employee.cs
   
public class Employee
    {
        public int ID  {get;set;}
        [Required]
        [MinLength(10)]
        public string Name {get;set;}
        [DisplayName("Date of Birth")]
        [DisplayFormat(DataFormatString= "{0:dd/MM/yy}", ApplyFormatInEditMode= true)]
        [AgeValidate]
        public string DOB { get; set; }
    }
EmployeeController.cs
   
public class EmployeeController : Controller
    {
        public ActionResult Index()
        {
            return View();
        }
        [HttpGet]
        public ActionResult Registration()
        {
            return View();
        }
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Registration(Employee emp)
        {
            if(!ModelState.IsValid)
            {
                return View("Registration", emp);
            }
            return View();
        }
    }
Registration.cshtml
   
@model DataAnnotationTest.Models.Employee

@{
    ViewBag.Title = "Registration";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

Registration

@using (Html.BeginForm()) { @Html.AntiForgeryToken()

@Html.ValidationSummary(true, "", new { @class = "text-danger" })
@Html.LabelFor(model => model.Name, htmlAttributes: new { @class = "control-label col-md-2" })
@Html.EditorFor(model => model.Name, new { htmlAttributes = new { @class = "form-control" } }) @Html.ValidationMessageFor(model => model.Name, "", new { @class = "text-danger" })
@Html.LabelFor(model => model.DOB, htmlAttributes: new { @class = "control-label col-md-2" })
@Html.EditorFor(model => model.DOB, new { htmlAttributes = new { @class = "form-control" } }) @Html.ValidationMessageFor(model => model.DOB, "", new { @class = "text-danger" })
}
@Html.ActionLink("Back to List", "Index")
Now run the application and see How does it work in MVC application ?
AntiForgeryToken in MVC Framework
Fig - 1
Token value stored in hidden field see in fig -1
AntiForgeryToken in MVC Framework
Fig - 2
Token value also stored in browser cookies. see in fig -2 

as you see in above example,  AntiForgeryToken used in view as HTML Helper method and Action attribute on action method.