简体   繁体   中英

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

我遇到了同样的麻烦,没有ajax破坏调用结果我只是错过旧布局标题中的<%= csrf_meta_tag%>。

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM