Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 724
Dario Barrionuevo Avatar asked Mar 13 '11 16:03

Dario Barrionuevo


2 Answers

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;
    }
  }
});
like image 83
Yura Omelchuk Avatar answered Nov 15 '22 18:11

Yura Omelchuk


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.

like image 38
Paul Raupach Avatar answered Nov 15 '22 16:11

Paul Raupach