Dimitar Kostov ramblings

Cookie based authentication strategy in Devise

This method assumes that you have token authentication strategy enabled and will use the token for the user for cookie authentication

lib/devise/cookie_token_auth_strategy.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
Warden::Strategies.add(:token_cookie_strategy) do
  def valid?
    token_from_cookie
  end

  def authenticate!
    if token_from_cookie.present? && (user = User.find_for_token_authentication(:auth_token => token_from_cookie)).present?
      delete_token_from_cookie
      success!(user)
    else
      fail!("Could not log in")
    end
  end

  def token_from_cookie
    cookies[:authentication_token]
  end

  def delete_token_from_cookie
    cookies.delete(:authentication_token)
  end

end
config/initializers/devise.rb
1
2
3
4
5
Devise.setup do |config|
  config.warden do |manager|
    manager.default_strategies(:scope => :user).unshift :token_cookie_strategy
  end
end
config/application.rb
1
2
3
4
5
6
module YourApp
  class Application < Rails::Application
    config.autoload_paths += %W(#{config.root}/lib/devise)
    # rest of the file
  end
end

Comments