2013-03-27 17 views

Trả lời

17

Từ những gì tôi có thể hiểu được từ docs, http_basic_authenticate_with hoạt động như một trước khi lọc mà chấp nhận một tên và mật khẩu như

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

Trong khi authenticate_or_request_with_http_basic chấp nhận một khối cho phép bạn chèn một số mã để xác định xem họ nên được chứng thực (documentation). Ví dụ.

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 

(Hãy cẩn thận, ví dụ này có thể không an toàn. Ví dụ, hiện nay nó là không an toàn vì nó sử dụng secure_compare thay vì variable_size_secure_compare. Xem source code của http_basic_authenticate_with trong ActionController::HttpAuthentication từ phiên bản hiện tại của Rails cho một an toàn hơn Ví dụ.)

+0

Để kiểm tra điều này với Capybara, hãy xem http://stackoverflow.com/a/7938935/664833 – user664833

+1

Và ** để kiểm tra ở cấp bộ điều khiển **, sử dụng '@ request.env ['HTTP_AUTHORIZATION'] = 'Basic' + Base64 :: encode64 ('tên người dùng: mật khẩu') 'rồi' get: your_action'. Tham khảo: http://apidock.com/rails/ActionController/HttpAuthentication/Basic/ControllerMethods/authenticate_or_request_with_http_basic#197-Testing-protected-controllers – user664833

+0

'http_basic_authenticate_with' thực sự gọi' authenticate_or_request_with_http_basic' nội bộ. Xem [source] (https://github.com/rails/rails/blob/master/actionpack/lib/action_controller/metal/http_authentication.rb#L69). – mlovic