2013-03-27 50 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