Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ruby-on-rails/52.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails 某些(并非所有)控制器的HTTP基本身份验证_Ruby On Rails_Authentication - Fatal编程技术网

Ruby on rails 某些(并非所有)控制器的HTTP基本身份验证

Ruby on rails 某些(并非所有)控制器的HTTP基本身份验证,ruby-on-rails,authentication,Ruby On Rails,Authentication,使用Rails 3.2 我有六个控制器,想用http\u basic\u authenticate\u保护其中的一些(但不是全部) 我不想手动向每个控制器添加http\u basic\u authenticate\u(我可能会在将来添加另一个控制器,而忘记保护它!)。答案似乎是将其放入应用程序\u controller.rb中,并带有:除了将列出不应保护的控制器的arg。问题是:except子句需要方法名而不是外部控制器模块名,例如: http_basic_authenticate_with :

使用Rails 3.2

我有六个控制器,想用
http\u basic\u authenticate\u
保护其中的一些(但不是全部)

我不想手动向每个控制器添加
http\u basic\u authenticate\u
(我可能会在将来添加另一个控制器,而忘记保护它!)。答案似乎是将其放入
应用程序\u controller.rb中,并带有
:除了将列出不应保护的控制器的
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\u basic\u authenticate\u使用
所做的只是在操作之前添加一个
。你自己也可以轻松做到这一点:

# 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\u before\u action

# unprotected_controller.rb

skip_before_action :http_basic_authenticate

一个选项是使用
类ProtectedController
,将
http\u basic\u authenticate
放在那里,并从中继承受保护的控制器。如果您碰巧使用designe进行身份验证,您可以使用designe而不是rails启用基本身份验证-可能与您的情况无关?Sergio,这会让我回到我试图避免的地方——我必须手动添加我想要保护的每个新控制器。如果我愿意这样做,我可以简单地将http_base_authenticate行放入每个控制器。@house9我没有听说过Desive,谢谢你的提示。我去看看。谢谢你。这应该是公认的答案。