Search code examples
securityasp.net-mvc-2xssantiforgerytoken

How does AntiForgeryToken work?


I am applying Security to my .net 3.5 mvc2 web application. My website doesn't contain any user authentication and consists of many ajax calls in .js files

In my .aspx file I wrote

<%= Html.AntiForgeryToken() %>   

In my .js file function I wrote

$(document).ready(function() {

var token = $('input[name=__RequestVerificationToken]').val();

    $.ajax({
    url: "/Home/getCurrentLanguage/" + Math.random(),
        cache: false,
        type: "POST",
        async: false,
        data: {"__RequestVerificationToken":token},
        success: function(data) {
            if (data == "mr") {
                alert("its Marathi");
            } else {
                alert("its English huh !!!");
            }
            return false;
        },
        error: function(data) {
            alert("some Error" + data);
        }
    });

});

In my Controller I wrote

    [AcceptVerbs(HttpVerbs.Post), ValidateAntiForgeryToken]
    public JsonResult getCurrentLanguage(string id)
    {
        return new JsonResult
        {
            Data = "mr"
        };

    }

This works fine for me, but I have 2 Questions
Q1. Is it the correct approach ? If I see the page source, I found this code

<input name="__RequestVerificationToken" type="hidden" value="WFd+q5Mz0K4RHP7zrz+gsloXpr8ju8taxPJmrLO7kbPVYST9zzJZenNHBZqgamPE1KESEj5R0PbNA2c64o83Ao8w8z5JzwCo3zJKOKEQQHg8qSzClLdbkSIkAbfCF5R6BnT8gA==" /> 

but when I created the external html file and copy this value of __RequestVerificationToken and pass in ajax call, I am getting this error
A required anti-forgery token was not supplied or was invalid. then
Q2. How does runtime know that this page is supplying the copied __RequestVerificationToken?


Solution

  • This "AntiForgeryToken" is in place to prevent Cross-Site Request Forgery attacks. This system can be undermined by an attacker if your application suffers from a Cross-Site Scripting vulnerability.

    This token prevents CSRF attacks because due to the same-origin policy the attacker can send requests but he cannot read the token off of the page to make the request succeed (unless he has an xss vulnerability).

    As for Q2, this value must be unique per user and therefore updated each time the page loads. If its just a static value, then its useless at stopping CSRF because the attacker will know this same static value.