设计的自定义认证策略

ops*_*psb 26 ruby ruby-on-rails devise

我需要为https://github.com/plataformatec/devise编写自定义身份验证策略,但似乎没有任何文档.怎么做的?

ops*_*psb 39

我在设计谷歌组的这个帖子中找到了这个非常有用的片段

初始化/ 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 
Run Code Online (Sandbox Code Playgroud)

将以下内容添加到initializers/devise.rb中

  config.warden do |manager| 
     manager.default_strategies.unshift :custom_strategy_name 
  end 
Run Code Online (Sandbox Code Playgroud)

  • 我强烈建议您在实施自己的策略时使用[DatabaseAuthenticatable](https://github.com/plataformatec/devise/blob/master/lib/devise/strategies/database_authenticatable.rb)作为模板,否则您可能会遇到问题记忆不起作用,其设置是在[valid]的调用中完成的(https://github.com/plataformatec/devise/blob/master/lib/devise/strategies/authenticatable.rb#L28-L45). (3认同)