Preventing Cross Site Request Forgery attack in MVC

 It is a method of attacking website from malicious or fake site send request to valid or vulnerable website where the user is logged In, we should know that all web application platform is vulnerable from CSRF that is cross site request forgery attack it is also known as XSRF. We can prevent it from the Anti-Forgery Token. 

Antiforgery token is mainly used in form post action to verify posted data. In every request the web server sends a cookie to the client browser while posting data or next request time. When user submit data MVC framework checks for a request forgery it also check that _Request-VerificationToken Hidden Field and _Request-verification Token. 

Now we will take an example to understand this 

Cross Site Request Forgery is an attack in which User or Victim is already login to Valid site (abc.Com) and in same way Victim open some other Malicious site in another tab then Malicious site send request to valid site (abc.Com) using logged in session of victim for attack as (abc.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.  

Adding @Html.AntiForgeryToken() to Index view 

For saving from attack of cross site request forgery attack we need to add antiforgery token as shown below


@model CodeFirstApproch_Demo.Models.Student
    Layout = null;
<!DOCTYPE html>
    <meta name="viewport" content="width=device-width" />
        @using (Html.BeginForm("Index","Home",FormMethod.Post))
       <span>Name</span> @Html.TextBoxFor(x=>x.Name);<br />
       <span>Father Name</span>  @Html.TextBoxFor(x=>x.Father_Name);<br />
       <span>Email</span>  @Html.TextBoxFor(x=>x.Email);<br />
        <span>Address</span> @Html.TextBoxFor(x=>x.Address);<br />
            <span>Date of Birth</span>@Html.TextBoxFor(x => x.Dob, new {type="date"});<br />
        <input type="submit" />@ViewBag.msg

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


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Data;
using CodeFirstApproch_Demo.Models;
namespace CodeFirstApproch_Demo.Controllers
    public class HomeController : Controller
        // GET: /Home/
        public ActionResult Index()
            return View();
        public ActionResult Index(Student Model)
            using (var ctx = new School_Context())
                ViewBag.msg = "Record Saved!!";
                return View();

Now if hacker tries to hack then this error will be generated .

Last updated:9/7/2019 12:17:27 AM


Leave Comment