From 1109a4500f0d90790e307ddcfff8743ca195e80e Mon Sep 17 00:00:00 2001 From: Paul Chavard Date: Tue, 21 Aug 2018 11:31:42 +0200 Subject: [PATCH] Add csrf token protection to jQuery initiated requests --- app/javascript/shared/rails-ujs-fix.js | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/app/javascript/shared/rails-ujs-fix.js b/app/javascript/shared/rails-ujs-fix.js index 19aac8054..a7cc7eb5e 100644 --- a/app/javascript/shared/rails-ujs-fix.js +++ b/app/javascript/shared/rails-ujs-fix.js @@ -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); + } +}