Using devise “rememberable” without cookies

2019-03-31 11:13发布

问题:

I have a working Rails site that uses devise to manage users. For session management, I am using devise's rememberable strategy, which stores and retrieves encrypted authentication information from a user's cookie.

I'm implementing a multi-photo upload widget that uses flash. Flash does not support sending cookies along with requests. This is a problem with multiple multi-upload flash+javascript libraries, so fixing this shortcoming is probably not feasible.

So my question is: can I successfully authenticate to devise/rememberable without using cookies? And if so, how?

More details

Devise/rememberable depends on the value of remember_token within the cookie. If I could fool Rails into thinking that the value was supplied as a cookie (e.g. request.cookies['remember_token'] = '...'), my problem would be solved. Devise/rememberable would find the correct value there, unpack it, and successfully authenticate. However, the request.cookies hash is apparently read-only. Writing to the hash is silently ignored. Example (debug console from an incoming POST request):

>> request.cookies['remember_token'] = 'a string'
=> "a string"
>> request.cookies['remember_token']
=> nil
>> request.cookies
=> {}

I'm using (or trying to use) the FancyUpload v3 widget.

回答1:

How about overriding Devise slightly?

Based on Devise 1.2.rc something like this should work:

module Devise
  module Strategies
    class Rememberable
      def remember_cookie
        # your code to get the hashed value from the request
      end
    end
  end
end

Alternatively, you could add a new (subclassed) strategy:

module Devise
  module Strategies
    class RememberableParameter < Rememberable
      def remember_cookie
        # your code to get the hashed value from the request
      end
    end
  end
end
Warden::Strategies.add(:rememberable_parameter, Devise::Strategies::Rememberable)

Or, look into Token Authenticatable:

Token Authenticatable: signs in a user based on an authentication token (also known as "single access token"). The token can be given both through query string or HTTP Basic Authentication

There's more about it here: https://github.com/plataformatec/devise/blob/master/lib/devise/models/token_authenticatable.rb

Good luck!