CSRF – AntiForgeryToken and AJAX

Below shows how to apply an Cross Site (anti) Forgery – CSRF) token to MVC page that posts data using Ajax. This is converted from the following stackoverflow question here.

First wire up the ajax call and check it works. Then add the [ValidateAntiForgeryToken] and [HttpPost] attribute to your action in the controller. At this point your ajax call to the action will begin to fail as the validate anti forgery system kicks in. Make sure if you remove the [ValidateAntiForgeryToken] the request still works, now reapply it.

That is the server side secured, next we need to add the token to the client side. First add a form element with an anti forgery token to your view or to your layout page as below:

<form id=”__AjaxAntiForgeryForm” action=”#” method=”post”>

@Html.AntiForgeryToken()

</form>

Now add a JavaScript function to your view to append the CSRF anti forgery token to the data. This finds the form element and pulls the anti forgery token from it.

AddForgeryToken = function(data) {

     data.__RequestVerificationToken = $(‘#__AjaxAntiForgeryForm input[name=__RequestVerificationToken]’).val();

    return data;

};

Now wrap the data to be sent with the AddForgeryToken function as below

            $.ajax({

                dataType: “json”,

                type: “POST”,

                url: “DeleteOrder”,

                data: AddForgeryToken({ myId: value }),

                success: function (response) {

                    …blah blah

                }

            });

The request should now work.

One thought on “CSRF – AntiForgeryToken and AJAX

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s