某些(不是所有)控制器的HTTP Basic Auth

使用Rails 3.2。

我有六个控制器,并想用http_basic_authenticate_with来保护它们中的一些 (但不是全部)。

我不想手动将http_basic_authenticate_with添加到每个控制器(我可以在将来添加另一个控制器而忘记保护它!)。 似乎答案是将它放在application_controller.rb ,其中:except arg,它将列出不应受保护的控制器。 问题是,:except子句需要方法名称而不是外部控制器模块名称,例如:

 http_basic_authenticate_with :name => 'xxx', :password => 'yyy', :except => :foo, :bar 

然后我想“等等,因为我已经将受保护的控制器分组在routes.rb ,让我们把它放在那里。” 所以我在我的路线中试过这个:

  scope "/billing" do http_basic_authenticate_with :name ... resources :foo, :bar ... end 

但现在我明白了

 undefined method `http_basic_authenticate_with' 

什么是最好的方法来解决这个问题?

按照Rails的方式做到这一点。

 # rails/actionpack/lib/action_controller/metal/http_authentication.rb def http_basic_authenticate_with(options = {}) before_action(options.except(:name, :password, :realm)) do authenticate_or_request_with_http_basic(options[:realm] || "Application") do |name, password| name == options[:name] && password == options[:password] end end end 

http_basic_authenticate_with所做的就是添加一个before_action 。 您可以轻松地自己做同样的事情:

 # application_controller.rb before_action :http_basic_authenticate def http_basic_authenticate authenticate_or_request_with_http_basic do |name, password| name == 'xxx' && password == 'yyy' end end 

这意味着您可以在不需要此行为的控制器中使用skip_before_action

 # unprotected_controller.rb skip_before_action :http_basic_authenticate