CSRF Protection in AJAX Requests using MVC2 CSRF Protection in AJAX Requests using MVC2 ajax ajax

CSRF Protection in AJAX Requests using MVC2


You could use the conventional Html.AntiForgeryToken() helper to generate a hidden field somewhere on the page (not necessarily inside a form) and include it along the ajax request:

var token = $('input[name=__RequestVerificationToken]').val();$.post(    '/SomeAction', { '__RequestVerificationToken': token },     function() {        alert('Account Deleted.');    });

To verify it on the server side:

[AcceptVerbs(HttpVerbs.Post)][ValidateAntiForgeryToken]public ActionResult SomeAction() {    return View();}

If you have multiple tokens on your page you might need to specify which one to include. As the existing helper generates the hidden fields with the same names it is difficult to make a good selector so you could place them inside spans:

<span id="t1"><%= Html.AntiForgeryToken() %></span><span id="t2"><%= Html.AntiForgeryToken() %></span>

and then select the corresponding token:

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