简体   繁体   English

设计的自定义身份验证策略使用:token_authenticable

[英]Custom Authentication Strategy for Devise Using :token_authenticable

I am wondering how to implement a custom authentication strategy with devise using devise :token_authenticable . 我想知道如何使用devise :token_authenticable实现自定义身份验证策略。

I already found instructions on how to do it with a model using devise :database_authenticatable which is covered here . 我已经找到了如何使用devise :database_authenticatable进行模型的说明devise :database_authenticatable这里有介绍。

The model im trying to authenticate is named Pupil . 我试图验证的模型被命名为Pupil So here is my current strategy (located in config/initializers/custom_auth.rb ): 所以这是我当前的策略(位于config/initializers/custom_auth.rb ):

Warden::Strategies.add(:auth_pupil_strategy) do
  # missing valid? method indicates this strategy is always applied

  def authenticate!
    fail!("YOU SHALL NOT PASS!")
  end
end

And in my config/initializers/devise.rb (also tried it without the :scope => :pupil ): 在我的config/initializers/devise.rb (也试过没有:scope => :pupil ):

config.warden do |manager|
  manager.default_strategies(:scope => :pupil).unshift :auth_pupil_strategy
end

So this should lead to the user not beeing able to login, but somehow this strategy is not applied when switching from devise :database_authenticatable to devise :token_authenticable . 所以这应该导致用户无法登录,但是当从devise :token_authenticable devise :database_authenticatable切换到devise :token_authenticable时,不会以某种方式应用此策略。

Maybe I'm just missing the right :scope here. 也许我只是错过了右边:scope在这里。

Now, here's the strange thing: Whenever a user enters an invalid token my strategy is invoked and "YOU SHALL NOT PASS!" 现在,这是奇怪的事情:每当用户输入无效令牌时,我的策略被调用并且“你不应该通过!” is returned. 退回。 However when the correct token is supplied, the user can log in just fine. 但是,当提供正确的令牌时,用户可以正常登录。

Your strategy is not been called because you need to override the valid? 您的策略未被调用,因为您需要覆盖有效的策略? method as this answer suggest; 这个答案建议的方法;

But also you should use the default strategies method, however the way it was intended to be used is another, let see the declaration 但是你也应该使用默认策略方法,但是它的使用方式是另一种,让我们看一下声明

def default_strategies(*strategies)
  opts  = Hash === strategies.last ? strategies.pop : {}
  hash  = self[:default_strategies]
  scope = opts[:scope] || :_all

  hash[scope] = strategies.flatten unless strategies.empty?
  hash[scope] || hash[:_all] || []
end

as you can see the method is supposed receive an array of strategies, no just the scope, using unshift is a clever hack that puts your strategies at the top of the heap, but for some reason has unexpected behavior when is working with multiple custom strategies 正如你所看到的那样,该方法应该接收一系列策略,不仅仅是范围,使用unshift是一个聪明的黑客,它将你的策略放在堆的顶端,但由于某些原因,当使用多个自定义策略时出现意外行为

hope helps 希望有所帮助

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM