Merge pull request #2430 from tchak/jquery-csrf

Add csrf token protection to jQuery initiated requests
This commit is contained in:
Paul Chavard 2018-08-22 12:35:37 +00:00 committed by GitHub
commit a362e77b82
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23

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);
}
}