Custom Authentication Strategy for Devise Using :token_authenticable
Asked Answered
J

1

6

I am wondering how to implement a custom authentication strategy with devise using devise :token_authenticable.

I already found instructions on how to do it with a model using devise :database_authenticatable which is covered here.

The model im trying to authenticate is named Pupil. So here is my current strategy (located in 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.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.

Maybe I'm just missing the right :scope here.

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.

Jewry answered 2/5, 2013 at 10:20 Comment(3)
Shame that nobody was able to help you with this. Were you able to find a solution?Bewilderment
maybe kyan.com/blog/2013/10/11/devise-authentication-strategies will help?Enlistment
You have to implement a 'valid?' method for your strategy as well. I don't know if that'll solve anything, but it sure is a prerequisite for any strategy (see e.g. John Beynon's link).Maestro
K
0

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

hope helps

Kidron answered 26/6, 2015 at 17:8 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.