开发者

Devise logout when trying to destroy an object (Rails 3.0.5 & Devise 1.1.8)

I upgraded to Rails 3.0.5 & Devise 1.1.8. When I try to delete any object (through a view with :remote => true),开发者_JAVA技巧 I get an authentication dialog and the Devise session is destroyed. Then, I have to login again, and the object is still there... does anyone else have this problem? Any ideas on how to solve it?

Thank you very much.


This problem is not related to Devise. In short, since Rails 3.0.4 it is required that every non-GET request should have CSRF token, otherwise session gets cleared.

There are two major changes in this fix, the behaviour when CSRF protection fails has changed and the token will now be required for all non-GET requests.

After applying this patch failed CSRF requests will no longer generate HTTP 500 errors, instead the session will be reset. Users can override this behaviour by overriding handle_unverified_request in their own controllers.

More details here: http://weblog.rubyonrails.org/2011/2/8/csrf-protection-bypass-in-ruby-on-rails

jQuery snippet to use with your AJAX requests

$(document).ajaxSend(function(e, xhr, options) {
  var token = $("meta[name='csrf-token']").attr("content");
  xhr.setRequestHeader("X-CSRF-Token", token);
});

If you're using prototype, you'll need the following code:

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;
    }
  }
});


I was having the same trouble with none ajax destroy calls turns out I was just missing the <%= csrf_meta_tag %> in the header of my old layouts.


I am using rails 3.0.5 and simply replacing my public/javascript/rails.js with the latest one from here ( https://github.com/rails/jquery-ujs/blob/master/src/rails.js ) fixed this issue!!

PS : That rails.js should be used when you are using only jquery!


I had the same problem in Rails 3.0.5 + Devise (1.x + 1.2RC): User is being logged out on certain AJAX-requests.

The only solution to avoid this for now is downgrading Rails to 3.0.3.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜