Using Antiforgery with Ajax Jquery Call<!-- --> | <!-- -->Patrick Desjardins Blog
Patrick Desjardins Blog
Patrick Desjardins picture from a conference

Using Antiforgery with Ajax Jquery Call

Posted on: June 25, 2015

Using Antiforgery is pretty straightforward with normal form. You need to add an attribute on the top of the action and use a simple Html helper inside your form. The attribute will check for a specific value in session that has been calculated to be unique for the form. The Html helper create an hidden field with the value. Once the request is sent to the server, a comparison between the hidden field and the value in session is done. If they are not equal, an exception is thrown. This is a security mechanism that increase the security against malicious use of your cookie. For example, no one can just force a user to post a form that use the cookie for credential because this one will miss the antiforgery token. That said, with Ajax you have to do a little bit more.

First, you still need to add the antiforgery token at the top of your controller's action.

3public ActionResult SymbolChangeList(SymbolToRenameAddViewModel symbolToSave) {
4 //...

The helper is also required. You have different option. First, you can re-use an existing antiforgery html helper if your page already have a form that is currently use this mechanism. For example, the login/logout form at the top of your site is using this by default. However, I prefer to create one for the Ajax call. It allows me to create an unique html's container to have an easy access to it in JavaScript.

1<div id="anti-forgery-token"> @Html.AntiForgeryToken() </div>

From there, you just need to add the value of the hidden field inside your post arguments.

1$.ajax({ url: "/yourpage/here", type: 'POST', data: { idSymbolRename: id, /*Others variables to send */,__RequestVerificationToken: $('#anti-forgery-token [name=__RequestVerificationToken]').val() }, cache: true, dataType: 'json', success: function (json) {
2 // Success code here
3 },
4 error: function (xmlHttpRequest, textStatus, errorThrown) {
5 // Error code here
6 }

As you see, we need to specify a value for the __RequestVerificationToken value and we get this one from the generated hidden field from the Html Helper.

This code does not require a lot of modification from any Ajax call done with JQuery. The only detail that change is that you need to add the request verification token into the data sent to the server and you are up to go with a protected Post method.