2013-03-27 47 views

回答

17

从我可以从docshttp_basic_authenticate_with行为理解为前过滤器,它接受用户名和密码,如

http_basic_authenticate_with :name => "dhh", :password => "secret", :except => :index 

而authenticate_or_request_with_http_basic接受块允许你插入一些代码,以确定它们是否应该被认证(documentation)。例如。

before_filter :authenticate 

def authenticate 
    authenticate_or_request_with_http_basic('Administration') do |username, password| 
    ActiveSupport::SecurityUtils.secure_compare(username, "admin") && 
    ActiveSupport::SecurityUtils.secure_compare(password, "password") 
    end 
end 

(注意,这个例子可能是不安全的。例如,目前它是不安全的,因为它使用secure_compare而不是variable_size_secure_compare见的http_basic_authenticate_withsource codeActionController::HttpAuthentication Rails中的当前版本更安全例如。)

+0

要测试这与水豚,请参阅http://stackoverflow.com/a/7938935/664833 – user664833 2014-02-03 22:03:26

+1

和**以在控制器级**进行测试,使用'@ request.env ['HTTP_AUTHORIZATION'] ='Basic'+ Base64 :: encode64('username:password')''然后'get:your_action'。参考文献:http://apidock.com/rails/ActionController/HttpAuthentication/Basic/ControllerMethods/authenticate_or_request_with_http_basic#197-Testing-protected-controllers – user664833 2014-02-03 22:43:46

+0

'http_basic_authenticate_with'实际上是调用'内部authenticate_or_request_with_http_basic'。参见[源(https://github.com/rails/rails/blob/master/actionpack/lib/action_controller/metal/http_authentication.rb#L69)。 – mlovic 2017-01-10 17:25:44