Add csrf token protection to jQuery initiated requests

This commit is contained in:
Paul Chavard 2018-08-21 11:31:42 +02:00
parent 9ea36717ec
commit 1109a4500f

View file

@ -24,3 +24,22 @@ addEventListener('load', () => {
return element.href || href(element);
};
});
// rails-ujs installs CSRFProtection for its own ajax implementation. We might need
// CSRFProtection for jQuery initiated requests. This code is from jquery-ujs.
jQuery.ajaxPrefilter((options, originalOptions, xhr) => {
if (!options.crossDomain) {
CSRFProtection(xhr);
}
});
function csrfToken() {
return jQuery('meta[name=csrf-token]').attr('content');
}
function CSRFProtection(xhr) {
let token = csrfToken();
if (token) {
xhr.setRequestHeader('X-CSRF-Token', token);
}
}