回答你的如何從請求的憑證問題是:
user, pass = ActionController::HttpAuthentication::Basic::user_name_and_password(request)
然而authenticate_or_request_with_http_basic是所有你需要做的基本身份驗證:
class BlahController < ApplicationController
before_filter :authenticate
protected
def authenticate
authenticate_or_request_with_http_basic do |username, password|
# you probably want to guard against a wrong username, and encrypt the
# password but this is the idea.
User.find_by_name(username).password == password
end
end
end
authenticate_or_request_with_http_basic將返回401狀態,如果沒有提供證書,將在瀏覽器中彈出用戶名/密碼對話框。如果給出了詳細信息,那麼將傳遞給提供的塊。如果該塊返回true,則請求會通過。否則,請求處理被中止,並將403狀態返回給客戶端。
您還可以檢查出Railscast 82(那是上面的代碼是從): http://railscasts.com/episodes/82-http-basic-authentication
這是一個非常有用的答案 - 這看似簡單的閱讀這件事,但是我想知道如何做到這一點。感謝發佈。 – 2012-09-08 03:02:42