ASP.NET MVC AntiForgeryToken with Ajax

Not too long ago when I first started using ASP.NET MVC, Ajax, and the various web technologies, I was faced with the challenge of sending data back to the server using Ajax. I wanted to implement a solution that utilized the security features built into ASP.NET MVC, specifically using the AntiForgeryToken to avoid Cross Site Request Forgeries. Safe to say, back then i left that task undone. Today i decided to revisit that problem, and after a bit of googling I found that the antiforgerytoken needs to be sent manually. The following discusses my implementation.

If you use scaffolding to generate your controllers and views, it will take care of including the ValidateAntiForgeryToken() attribute on your controller action, and the @Html.AntiForgeryToken() in your razor view, within a form tag. When the form is submitted, the AntiForgeryToken is sent along to the server.

If, however, you make an Ajax call (a post) to the server, say, on a button click, the AntiForgeryToken is not automatically sent to the server.

Sample Ajax Call:

@Html.AntiForgeryToken()

<div...
</div>
.
.
.
<script>
    function SendData() {
        var options = {
            url: '@Url.Action("Create","Car")',
            type: "post",
            data: {
                regNumber: $("#regNumber").val(),
                make: $("#make").val(),
                model: $("#model").val()
            }
        };
        $.ajax(options);
    }
</script>

Internet Explorer Developer Tools Output showing the request and response body for the same request:

Error-AjaxRequestBody


Error-AjaxResponseBody2

So, the request body did not have the antiforgerytoken (neither did the header of course). Now lets manually add the antiorgerytoken:

<script>
    function SendData() {
        var token = $("[name='__RequestVerificationToken']").val();
        var options = {
            url: '@Url.Action("Create","Car")',
            type: "post",
            data: {
                __RequestVerificationToken: token,
                regNumber: $("#regNumber").val(),
                make: $("#make").val(),
                model: $("#model").val()
            }
        };
        $.ajax(options);
    }
</script>

As the output below shows, the request is successful this time around:

Success-AjaxRequest2

Advertisements

One thought on “ASP.NET MVC AntiForgeryToken with 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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s