Thursday, 12 May 2016

Cross-site Request Forgery in Asp.Net MVC

Here will learn what Cross- site Request forgery in Asp.net mvc  ,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 a attack in which a user login to a website like ABC.Com and after login user open other site called malicious site in other tab, then this malicious site send request to (ABC.com) valid site using existing credential or existing session for attacking the site, Valid site( ABC.com) assume that this coming request is a valid request or coming from a valid user , So it execute that request and site is hacked by the CSRF.

After recognizing this attack ,Microsoft provide a 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 a example using asp.net mvc
Go to visual studio and create a new project and select a Asp.net MVC4 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 “Besic” and view engine as “Rezor”.




After click ok it will create a project, After that right click on model folder and add a class name is “CollageInfo.cs”  ,and write the following code to this class
  public class CollageInfo
    {
        [Key]
        public int CollageID { get; set; }
        [Required(ErrorMessage = " please Enter Name")]
        public string CollageName { get; set; }
        [Required(ErrorMessage = "pleaes Enter Address")]
        public string CollageAddress { get; set; }
        [Required(ErrorMessage = "please Enter Department")]
        public string CollageDepartment { get; set; }

    }

After completion of model class we need to add a controller to this project so for that right click on the controller folder and a controller and give the name as “CollageController” with Empty MVC Controller template.


After adding controller we need to add action method name is “collageInfo” with [HttpGet] and [HttpPost]. So for that write the following code in controller collageInfo action method.
        [HttpGet]
        public ActionResult collageInfo()
        {
            return View();
        }

        [HttpPost]
        public ActionResult collageInfo(CollageInfo _clgInfo)
        {
            return View(_clgInfo);
        }

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 following


After click on  add it will generate code for the view ,following is the code for the view
@model CSRFInMVCApplication.Models.CollageInfo

@{
    ViewBag.Title = "collageInfo";
}

<h2>collageInfo</h2>

@using (Html.BeginForm()) {
    @Html.ValidationSummary(true)

    <fieldset>
        <legend>CollageInfo</legend>

        <div class="editor-label">
            @Html.LabelFor(model => model.CollageName)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.CollageName)
            @Html.ValidationMessageFor(model => model.CollageName)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.CollageAddress)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.CollageAddress)
            @Html.ValidationMessageFor(model => model.CollageAddress)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.CollageDepartment)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.CollageDepartment)
            @Html.ValidationMessageFor(model => model.CollageDepartment)
        </div>

        <p>
            <input type="submit" value="Create" />
        </p>
    </fieldset>
}

<div>
    @Html.ActionLink("Back to List", "Index")
</div>

@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
}


Now run your application, go to the following URL and see the output
http://localhost:50688/Collage/Collageinfo

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
After saving this file as .HTML ,Now open this file(.HTML)

Code for HTML file is
<html>
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width" />
    <title>collageInfo</title>
    <link href="/Content/site.css" rel="stylesheet"/>

    <script src="/Scripts/modernizr-2.6.2.js"></script>

</head>
<body>
   

<h2>collageInfo</h2>

<form action="http://localhost:50688/Collage/Collageinfo" method="post">    <fieldset>
        <legend>CollageInfo</legend>

        <div class="editor-label">
            <label for="CollageName">CollageName</label>
        </div>
        <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>

        <div class="editor-label">
            <label for="CollageAddress">CollageAddress</label>
        </div>
        <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>

        <div class="editor-label">
            <label for="CollageDepartment">CollageDepartment</label>
        </div>
        <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>

        <p>
            <input type="submit" value="Create" />
        </p>
    </fieldset>
</form>
<div>
    <a href="/Collage">Back to List</a>
</div>



    <script src="/Scripts/jquery-1.8.2.js"></script>

   
    <script src="/Scripts/jquery.unobtrusive-ajax.js"></script>
<script src="/Scripts/jquery.validate.js"></script>
<script src="/Scripts/jquery.validate.unobtrusive.js"></script>





</body>
</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 .


now enter some data and click on “create” button .


When you click on create button, you will see that this is redirecting to action method “CollageInfo” this wrong ,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

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

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
Like this we can prevent from this CSRF attack.


you can download this project from here Download


No comments:

Post a Comment

Paging in html table using javascript

I demonstrated how to use HTML tables on the client for a very simple client-side paging solution. I have heard from several people who p...