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

sha*_*ker 12 authentication ruby-on-rails

使用Rails 3.2.

我有六个控制器,并希望保护它们中的一些(但不是全部)http_basic_authenticate_with.

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

http_basic_authenticate_with :name => 'xxx', :password => 'yyy', :except => :foo, :bar
Run Code Online (Sandbox Code Playgroud)

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

  scope "/billing" do
    http_basic_authenticate_with :name ...
    resources :foo, :bar ...
  end
Run Code Online (Sandbox Code Playgroud)

但现在我明白了

undefined method `http_basic_authenticate_with'
Run Code Online (Sandbox Code Playgroud)

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

Sam*_*ake 37

按照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
Run Code Online (Sandbox Code Playgroud)

所有这一切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
Run Code Online (Sandbox Code Playgroud)

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

# unprotected_controller.rb

skip_before_action :http_basic_authenticate
Run Code Online (Sandbox Code Playgroud)

  • 感谢@SamBlake。这应该是公认的答案。 (2认同)