27

I need to write a custom authentication strategy for https://github.com/plataformatec/devise but there doesn't seem to be any docs. How's it done?

opsb
  • 29,325
  • 19
  • 89
  • 99

1 Answers1

42

I found this very helpful snippet in this thread on the devise google group

initializers/some_initializer.rb:

Warden::Strategies.add(:custom_strategy_name) do 
  def valid? 
    # code here to check whether to try and authenticate using this strategy; 
    return true/false 
  end 

  def authenticate! 
    # code here for doing authentication; 
    # if successful, call  
    success!(resource) # where resource is the whatever you've authenticated, e.g. user;
    # if fail, call 
    fail!(message) # where message is the failure message 
  end 
end 

add following to initializers/devise.rb

  config.warden do |manager| 
     manager.default_strategies.unshift :custom_strategy_name 
  end 
Fábio Batista
  • 25,002
  • 3
  • 56
  • 68
opsb
  • 29,325
  • 19
  • 89
  • 99
  • 1
    thanks, very useful, I've used it for authenticating my old website's joomla users :-) – simo Dec 20 '12 at 18:52
  • Very helpful answer, the link is broken though. Could you correct it? – mrzasa Jan 23 '13 at 11:28
  • 4
    I strongly recommend using [DatabaseAuthenticatable](https://github.com/plataformatec/devise/blob/master/lib/devise/strategies/database_authenticatable.rb) as a template when implementing your own strategies, or else you may experience issues with rememberable not working, whose setup is done in its call to [validate](https://github.com/plataformatec/devise/blob/master/lib/devise/strategies/authenticatable.rb#L28-L45). – Gabe Martin-Dempesy Feb 26 '14 at 20:35