Merge pull request #2430 from tchak/jquery-csrf
Add csrf token protection to jQuery initiated requests
This commit is contained in:
commit
a362e77b82
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