Information Security, Web, Networks and Systems

Thursday, April 17, 2014

Using Anti Forgery Tokens with AJAX in ASP.NET

As you know, we can use anti forgery tokens to prevent Cross Site Request Forgery. Usually we add an anti forgery token in a hidden form field of the form. Each time we post the form to the server, server validates the request using the token in the hidden form field and the other one which is sent as a Cookie. See this post in my blog for more detailed information.
              But when we use AJAX to post data to the server asynchronously, we do not use forms most of the times. In those cases we explicitely need to attach the anti forgery token to our data which is sent via ajax. We can do this by some simple javascript.
I am going to describe this approach I used in my application, for PHP, Java, this approach will be little bit different according to what library you use for CSRF protection. Here I use ASP.NET MVC with Razor view.

First, we will create a form in our parent page which includes only the Anti Forgery token.

<form id="AntiCSRFTokenForm"> @Html.AntiForgeryToken() </form>

Since this AntiForgeryToken is valid for the page, we can refer to this antiforgery token in any ajax request within the page. If you have many post request that requires request verification, you can inlude this line inside your layout page (or the master page).

Then, create a small script that you can access this token inside the form using a simple function call.

AddAntiCSRFToken = function (data) {
var token = $('#AntiCSRFTokenForm input[name=__RequestVerificationToken]').val();
data.__RequestVerificationToken = token;
return data;

This function simple takes a dictionary of data, adds anti forgery above created into the data dictionary and return updated data dictionary.

You can add above code snippet inside a .js file and include in any page where you need anti forgery token to be sent in ajax request.Then, you can send this token with a ajax request as follows.

Here is the jquery ajax request before adding anti forgery token.

    url : "/Controller/Action",
    type: "POST",
    data: {
         title: "this is title",
        age: 45

Here is the ajax request with anti forgery token.

    url : "/Controller/Action",
    type: "POST",
    data: AddAntiCSRFToken(
        title: "this is title",
        age: 45

Then you can use [ValidateAntiForgeryToken] attribute in your Controller action to validate the request.

1 comment:

Note: Only a member of this blog may post a comment.