关于如何从请求中获取凭据的问题的答案是这样的:
user, pass = ActionController::HttpAuthentication::Basic::user_name_and_password(request)
然而,authentication_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