Skip to content

Instantly share code, notes, and snippets.

@jamescrowley
Last active August 29, 2015 14:01
Show Gist options
  • Save jamescrowley/a6e53957c8c0778f5e12 to your computer and use it in GitHub Desktop.
Save jamescrowley/a6e53957c8c0778f5e12 to your computer and use it in GitHub Desktop.
Applying anti forgery tokens globally
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();
}
}
}
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