简体   繁体   中英

Can I control when a custom Devise/Warden strategy is run with before filters?

I'm developing a web application using Rails 3.2 and am using Devise and Warden for handling authentications.

I wanted to implement a custom authentication method for my app, so I read through Warden Wiki pages ( https://github.com/hassox/warden/wiki ) and created a custom Warden strategy with similar structure as the one showed in its documentation (I'll copy that below for the sake of clarity):

Warden::Strategies.add(:password) do

  def valid?
    params['username'] || params['password']
  end

  def authenticate!
    u = User.authenticate(params['username'], params['password'])
    u.nil? ? fail!("Could not log in") : success!(u)
  end

end

Following that, I added my custom "password" strategy to Devise appending the following code in config/initializers/devise.rb

config.warden do |manager|
    manager.default_strategies(:scope => :user).unshift :password
end

The problem I've found is that this authentication strategy is executed on every request, and I wanted to provide free access to certain requests to specific routes in my application. Initially, I thought of preventing the execution of the strategy using

skip_before_filter :authenticate_user!

on every controller whose actions doesn't require authentication, but the authentication keeps on executing even requesting to those controllers.

Can anybody help me how to skip the authentication in some requests? Or even more important, is my idea useless to achieve what I want?

Thanks in advance for your help. I really appreciate it.

Update

While debugging my code looking for a solution, I commented out all before_filter statements in all controller's code and discovered that the authentication strategy still executes. This behaviour turns out to be really strange to me. Does this make sense to anybody?

I can remember that your "skip filter" should call the autentication method. In this case you should replace skip_before_filter :authenticate_user! by skip_before_filter :authenticate!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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