Add csrf token protection to jQuery initiated requests
This commit is contained in:
parent
9ea36717ec
commit
1109a4500f
1 changed files with 19 additions and 0 deletions
|
@ -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);
|
||||
}
|
||||
}
|
||||
|
|
Loading…
Reference in a new issue