Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse files

send the "X-CSRF-Token" header with every Ajax request

  • Loading branch information...
commit e9311550fdb3afeb2917bcb1fef39767bf715003 1 parent e4fabba
@mislav mislav authored
View
20 src/rails.js
@@ -6,6 +6,26 @@
*/
(function($) {
+ // Make sure that every Ajax request sends the CSRF token
+ function CSRFProtection(fn) {
+ var token = $('meta[name="csrf-token"]').attr('content');
+ if (token) fn(function(xhr) { xhr.setRequestHeader('X-CSRF-Token', token) });
+ }
+ if ($().jquery == '1.5') { // gruesome hack
+ var factory = $.ajaxSettings.xhr;
+ $.ajaxSettings.xhr = function() {
+ var xhr = factory();
+ CSRFProtection(function(setHeader) {
+ var open = xhr.open;
+ xhr.open = function() { open.apply(this, arguments); setHeader(this) };
+ });
+ return xhr;
+ };
+ }
+ else $(document).ajaxSend(function(e, xhr) {
+ CSRFProtection(function(setHeader) { setHeader(xhr) });
+ });
+
// Triggers an event on an element and returns the event result
function fire(obj, name, data) {
var event = new $.Event(name);
View
9 test/public/test/call-remote.js
@@ -83,4 +83,13 @@ asyncTest('allow empty "data-remote" attribute', 1, function() {
});
});
+asyncTest('sends CSRF token in custom header', 1, function() {
+ build_form({ method: 'post' });
+ $('#qunit-fixture').append('<meta name="csrf-token" content="cf50faa3fe97702ca1ae" />');
+
+ submit(function(e, data, status, xhr) {
+ equal(data.HTTP_X_CSRF_TOKEN, 'cf50faa3fe97702ca1ae', 'X-CSRF-Token header should be sent');
+ });
+});
+
})();
View
3  test/public/test/data-method.js
@@ -13,10 +13,11 @@ function submit(fn) {
.trigger('click');
}
-asyncTest('link with "data-method" set to "delete"', 2, function() {
+asyncTest('link with "data-method" set to "delete"', 3, function() {
submit(function(data) {
equal(data.REQUEST_METHOD, 'DELETE');
strictEqual(data.params.authenticity_token, undefined);
+ strictEqual(data.HTTP_X_CSRF_TOKEN, undefined);
});
});
Please sign in to comment.
Something went wrong with that request. Please try again.