Permalink
Browse files

CSRF: fix Ajax on IE, include header only if token present

  • Loading branch information...
1 parent 900d714 commit a284dd706e7d76e85471ef39ab3efdf07feef374 @RStankov RStankov committed with mislav Feb 23, 2011
Showing with 4 additions and 16 deletions.
  1. +4 −16 src/rails.js
View
@@ -7,24 +7,12 @@
(function($) {
// Make sure that every Ajax request sends the CSRF token
- function CSRFProtection(fn) {
+ function CSRFProtection(xhr) {
var token = $('meta[name="csrf-token"]').attr('content');
- if (token) fn(function(xhr) { xhr.setRequestHeader('X-CSRF-Token', token) });
+ if (token) 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) });
- });
+ if ('ajaxPrefilter' in $) $.ajaxPrefilter(function(options, originalOptions, xhr){ CSRFProtection(xhr) });
+ else $(document).ajaxSend(function(e, xhr){ CSRFProtection(xhr) });
// Triggers an event on an element and returns the event result
function fire(obj, name, data) {

5 comments on commit a284dd7

@antidis

One issue here is that this prevents users from ever sending requests, in jQuery 1.5, without the X-CSRF-Token. This effectively breaks sending cross-domain stuff in apps that use rails.js, and it doesn't seem to be something you can over-ride in beforeSend (we're doing some cross-domain stuff so we noticed it breaking when we moved to jQuery 1.5).

@RStankov
Contributor

Possibly here we can add check for .crossDomain property and don't apply CSRF tocken then.

@antidis

Yeah, changing the line to

if ('ajaxPrefilter' in $) $.ajaxPrefilter(function(options, originalOptions, xhr){ if ( !options.crossDomain ) { CSRFProtection(xhr) } });

certainly solves our problem, but I haven't run any proper testing on it and wouldn't know where to start (particularly as it's now 3am in the morning here).

@mislav
Member
mislav commented on a284dd7 Apr 10, 2011

Please open an issue detailing how did we break cross-domain stuff. I don't have experience using it so don't spare on the details

@antidis
Please sign in to comment.