Last active
August 29, 2015 14:01
-
-
Save jamescrowley/a6e53957c8c0778f5e12 to your computer and use it in GitHub Desktop.
Applying anti forgery tokens globally
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
public class AntiForgeryTokenFilter : IAuthorizationFilter | |
{ | |
private readonly AcceptVerbsAttribute _verbs; | |
public AntiForgeryTokenFilter(HttpVerbs verbs) | |
{ | |
_verbs = new AcceptVerbsAttribute(verbs); | |
} | |
public void OnAuthorization(AuthorizationContext filterContext) | |
{ | |
if (_verbs.IsValidForRequest(filterContext, null)) | |
{ | |
AntiForgery.Validate(); | |
} | |
} | |
} | |
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
function setupGlobalCSRFAjax() { | |
var csrfToken = { '__RequestVerificationToken': $('input[name="__RequestVerificationToken"]').val() }; | |
$.ajaxPrefilter(function(options, originalOptions) { | |
// do not send data for GET | |
if (originalOptions.type === 'GET' || options.type === 'GET') { | |
return; | |
} | |
// we modify data, but alternative option is to add to header | |
// and update AntiForgeryTokenFilter to look there instead | |
if (typeof (options.data) === "string") { | |
options.data = options.data + "&" + $.param(csrfToken); | |
} else { | |
options.data = $.extend(originalOptions.data, csrfToken); | |
} | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment