我想知道如何使用 devise :token_authenticable
使用设计实现自定义身份验证策略.
我已经找到了有关如何使用 devise :database_authenticatable
使用模型进行操作的说明。涵盖here .
我尝试验证的模型名为 Pupil
.
所以这是我目前的策略(位于 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
而在我的
config/initializers/devise.rb
(也试过没有 :scope => :pupil
):config.warden do |manager|
manager.default_strategies(:scope => :pupil).unshift :auth_pupil_strategy
end
所以这应该会导致用户无法登录,但不知何故,当从
devise :database_authenticatable
切换时,此策略不适用。至 devise :token_authenticable
.也许我只是错过了正确的
:scope
这里。现在,奇怪的是:每当用户输入无效 token 时,我的策略就会被调用,并且“您不能通过!”被退回。
但是,当提供正确的 token 时,用户可以正常登录。
最佳答案
您的策略未被调用,因为您需要覆盖有效的?方法为 this回答建议;
但是你也应该使用默认的策略方法,但是它的使用方式是另一种,让我们看看 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
如您所见,该方法应该接收一系列策略,而不仅仅是范围,使用 unshift 是一种巧妙的技巧,可将您的策略置于堆的顶部,但由于某些原因,在使用多个自定义策略时会出现意外行为
希望有帮助
关于ruby-on-rails - 使用 :token_authenticable 的设计的自定义身份验证策略,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16335565/