Created
August 22, 2012 18:21
-
-
Save scottrippey/3428114 to your computer and use it in GitHub Desktop.
ASP.NET MVC AntiForgeryToken + AJAX = jQuery to the rescue
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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(); | |
} | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
i have the same problem