Rails:访问用于HTTP Basic Auth的用户名/密码?
我正在构建一个基本API,在该用户的登录名和密码被正确发送后,可以检索用户信息。
现在我正在使用这样的东西:
http://foo:bar@example.com/api/user.xml
所以,我需要做的是访问请求中发送的用户/密码( foo
和bar
),但不知道如何在Rails控制器中访问该信息。
然后我通过快速的User.find
检查这些变量,然后将它们设置为authenticate_or_request_with_http_basic
的用户名和密码变量。
我可能会以完全错误的方式看待这个问题,但这就是我现在所处的位置。 🙂
关于如何从请求中获取凭据的问题的答案是:
user, pass = ActionController::HttpAuthentication::Basic::user_name_and_password(request)
但是,authenticate_or_request_with_http_basic是您进行基本身份validation所需的全部内容:
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
rails插件Authlogic支持开箱即用的此function(以及更多function)。 您可以根据它来源,或者只是将其集成到现有的应用程序中。
编辑:
在挖掘Authlogic的源代码后,我发现这个文件使用以下代码来获取用户名和密码:
def authenticate_with_http_basic(&block) @auth = Rack::Auth::Basic::Request.new(controller.request.env) if @auth.provided? and @auth.basic? block.call(*@auth.credentials) else false end end
我会进一步了解一切,但我必须上床睡觉。 希望我有所帮助。