From 11061f410eca48c3a1922ade001bc54927e6b8c7 Mon Sep 17 00:00:00 2001 From: Michael Koziarski Date: Thu, 13 Jan 2011 11:05:52 +1300 Subject: [PATCH] Make rails.js include the CSRF token in the X-CSRF-Token header with every ajax request. --- .../public/javascripts/prototype_ujs.js | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/railties/lib/rails/generators/rails/app/templates/public/javascripts/prototype_ujs.js b/railties/lib/rails/generators/rails/app/templates/public/javascripts/prototype_ujs.js index 4c18cb0c3e..2cd1220786 100644 --- a/railties/lib/rails/generators/rails/app/templates/public/javascripts/prototype_ujs.js +++ b/railties/lib/rails/generators/rails/app/templates/public/javascripts/prototype_ujs.js @@ -189,4 +189,20 @@ document.on('ajax:complete', 'form', function(event, form) { if (form == event.findElement()) enableFormElements(form); }); + + Ajax.Responders.register({ + onCreate: function(request) { + var csrf_meta_tag = $$('meta[name=csrf-token]')[0]; + + if (csrf_meta_tag) { + var header = 'X-CSRF-Token', + token = csrf_meta_tag.readAttribute('content'); + + if (!request.options.requestHeaders) { + request.options.requestHeaders = {}; + } + request.options.requestHeaders[header] = token; + } + } + }); })();