Protect ASP.NET MVC Application from CSRF Attacks using Antiforgery Token

This article explains what is the CSRF attack and how you can use Antiforgerytokens to protect application from these attacks.

Below steps are given to create MVC application and use Antiforgery tokens in MVC view and Controller Action Methods.

What is CSRF Attacks?

Cross-site request forgery (XSRF or CSRF) is a method of attacking website by executing non trusted actions. Those attacks get executed by malicious users by stealing the identity of an existing user and then getting access to Web Server using that identity.

How CSRF Attacks get executed?

Let us see a example. I login to with my credentials visit some pages. This site has a page which is vulnerable to CSRF attacks. I did not logout from and visited a malicious website which has CSRF attacking code to This code transfer some amount to unauthorized account number. has below html

   <iframe src=">

When this iframe loads by browser, it sends a fund transfer request to On this request is valid as I did not log out and valid tokens are stored in browser. If tokens are not changed and validated on every request CSRF attacks are possible.

Prevent CSRF attacks

You can easily prevent those CSRF attacks in your MVC applications by appending unpredictable random tokesn with each request, attach it with user's session and validate it on Web Server.

Implementing AntiForgeryTokens in MVC

  1. Create a new MVC application by File -> New -> Project and select ASP.NET MVC application and name it to Antiforgery_in_mvc. You can visit Getting started with MVC for more info on MVC templates.

    Create a HomeController and index.cshtml files

  2. Now open index.cshtml file and add below HTML code. It has TextBox and a Button to submit form to GetMessage Action method.

       @using (Html.BeginForm("Getmessage", "Home"))
            @Html.Label("Enter your name:")
            <input type="submit" value="submit" />     

    Notice @Html.AntiForgeryToken(); it includes two tokens in the response. One token is sent as HTTP cookie and othe is included in form as hidden field.

    When you execute your page see the view source of page, you will notice a input field with name __RequestVerificationToken.

        <input name="__RequestVerificationToken" type="hidden"   
               value="6fGBtLasde77885qwafasdera44ad444aeadvhrgerhuk22wet[...]" />

    When the user submits form, client send both tokens to Web Server with POST request. See the details about MVC application request life cycle.

    Those tokens cannot be read by any other website because of same origin policy of browser.

  3. In this step you will implement a Action method which will validate those tokens sent by client to WebServer.

    Open HomeController and add GetMessage action method. Add below code as part of GetMessage

        public ActionResult Getmessage(string message)
            return View("Getmessage");

    When a POST request for GetMessage comes to the WebServer, [ValidateAntiForgeryToken] attribute validates the hidden field and cookie exist and has same value which were added to page while rendering. If it is true then only it process the action method. If not then attribute throws exception.

    Now executes your application and see the source by right click on page and select View Page Source. You will see hidden field is added to form.

    AntiForgeryToken hidden field

    Open developer tool by pressing F12 -> Open Resources tab -> From left pane click on Cookie

    AntiForgeryToken cookie

Download Source code

Speak your mind :
Leave a comment for this article on