Custom Authentication Strategy For Devise

Custom authentication strategy for devise

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

Devise lockable and custom strategy

I ended up using devise_custom_authenticatable in combination with the resources posted on the original question. For lockable to work, database_authenticable must be present. Toni's answer above should work if you have control over LDAP, which I did not when I posed the question.

Run warden strategy in devise when user is already authenticated

Before calling any strategies warden checks if there's already a stored user in session (from previous requests, where some strategy with store?=true (the default) has succeeded)

You can try faking a 'non-set' user (without full log out) by something like:

# manager is Warden::Manager
manager.prepend_on_request do |proxy|
proxy.set_user(nil, scope: :user, store: false) if proxy.env["HTTP_AUTHORIZATION"].present?
end

PS. your strategy probably should also have def store?; false; end, as api keys are usually required with each request, and also should not result in persisted session



Related Topics



Leave a reply



Submit