Skip to content

Instantly share code, notes, and snippets.

@justinperkins
Created October 26, 2012 17:48
Show Gist options
  • Star 20 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save justinperkins/3960219 to your computer and use it in GitHub Desktop.
Save justinperkins/3960219 to your computer and use it in GitHub Desktop.
Put auth-token on all jQuery Ajax Requests
$(function(){
var tokenValue = $("meta[name='csrf-token']").attr('content');
$.ajaxSetup({
headers: {'X-CSRF-Token': tokenValue}
});
})
@ses4j
Copy link

ses4j commented Aug 8, 2013

@pje: Nevertheless, in this case, I'd think adding a custom X- HTTP header is a pretty safe thing to do, it's not like you're changing the default url or data or something.

@BigglesZX
Copy link

Thanks for this – just one small note: I think the header needs to be X-CSRFToken not X-CSRF-Token according to this thread – didn't work for me until I changed that.

@davifiamenghi
Copy link

@ses4j: I think that would be undesirable to expose the authorization header on a $.get to a third part resource (for example images)

@marcin-krysiak
Copy link

This might be of your interest. This code extends jQuery Ajax to include token to the defined ajax requests types that was previously get from your server.

I successfully use that code in many projects

the url is here: https://github.com/marcinkrysiak1979/jquery-ajax-addToken

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment