Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Put auth-token on all jQuery Ajax Requests
$(function(){
var tokenValue = $("meta[name='csrf-token']").attr('content');
$.ajaxSetup({
headers: {'X-CSRF-Token': tokenValue}
});
})
@pje

This comment has been minimized.

Copy link

pje commented May 16, 2013

FWIW, $.ajaxSetup is pretty frowned-upon by the docs: http://api.jquery.com/jQuery.ajaxSetup

The settings specified here will affect all calls to $.ajax or AJAX-based derivatives such as $.get(). This can cause undesirable behavior since other callers (for example, plugins) may be expecting the normal default settings. For that reason we strongly recommend against using this API. Instead, set the options explicitly in the call or define a simple plugin to do so.

@ses4j

This comment has been minimized.

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

This comment has been minimized.

Copy link

BigglesZX commented Feb 21, 2014

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

This comment has been minimized.

Copy link

davifiamenghi commented Apr 29, 2014

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

@marcinkrysiak1979

This comment has been minimized.

Copy link

marcinkrysiak1979 commented Apr 23, 2015

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
You can’t perform that action at this time.