Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
ASP.NET MVC AntiForgeryToken + AJAX = jQuery to the rescue
// Setup CSRF safety for AJAX:
$.ajaxPrefilter(function(options, originalOptions, jqXHR) {
if (options.type.toUpperCase() === "POST") {
// We need to add the verificationToken to all POSTs
var token = $("input[name^=__RequestVerificationToken]").first();
if (!token.length) return;
var tokenName = token.attr("name");
// If the data is JSON, then we need to put the token in the QueryString:
if (options.contentType.indexOf('application/json') === 0) {
// Add the token to the URL, because we can't add it to the JSON data:
options.url += ((options.url.indexOf("?") === -1) ? "?" : "&") + token.serialize();
} else if (typeof options.data === 'string' && options.data.indexOf(tokenName) === -1) {
// Append to the data string:
options.data += (options.data ? "&" : "") + token.serialize();
}
}
});
@ghost

This comment has been minimized.

Copy link

commented Feb 4, 2013

Where do I declare this though? That is the only part I am confused about.

@arvinyorro

This comment has been minimized.

Copy link

commented Dec 7, 2013

For anyone else confused with this one, this is an event handle, just post this anywhere in your script.

@alpha-mouse

This comment has been minimized.

Copy link

commented Feb 25, 2014

It seems to me, there should be && !options.crossDomain in the condition too. Not to bug 3rd party services.

@ieski

This comment has been minimized.

Copy link

commented Sep 1, 2016

public static class HtmlHelper
{
public static string GetAntiForgeryToken()
{
System.Text.RegularExpressions.Match value = System.Text.RegularExpressions.Regex.Match(System.Web.Helpers.AntiForgery.GetHtml().ToString(), "(?:value=")(.*)(?:")");
if (value.Success)
{
return value.Groups[1].Value;
}
return "";
}
}

@arc95

This comment has been minimized.

Copy link

commented Mar 7, 2017

This really helped me out on a page with AJAX and pagination. The PagedList was failing because it wasn't passing the token. Thank you 💯

@JeffCodes85

This comment has been minimized.

Copy link

commented Apr 5, 2017

I cannot get this to work when the contentType is 'application/json'. I tried this as well as many variations/hacks (adding it in header instead, adding to the json data, etc.) and could not get it to work with json requests. Anyone else having this problem. If you're using this please confirm that you're successfully sending a json post with the 'ValidateAntiForgeryToken' attribute. According to this post "The problem lies in the fact that the under the hood, deep within the call stack, the attribute peeks into the Request.Form collection to grab the anti-forgery token. But when you post JSON encoded data, there is no form collection to speak of." You can't add to header as I tried because "the existing attribute which validates the token on the server won’t look in the header".

@weedkiller

This comment has been minimized.

Copy link

commented Jan 10, 2018

i have the same problem

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.