22

我正在构建一个基本 API,在正确发送用户的登录名和密码后可以检索用户信息。

现在我正在使用这样的东西:

http://foo:bar@example.com/api/user.xml

所以,我需要做的是访问请求中发送的用户/密码(foobar),但我不确定如何在 Rails 控制器中访问该信息。

然后我会通过快速检查这些变量User.find,然后将它们设置为authenticate_or_request_with_http_basic.

我可能以完全错误的方式看待这个问题,但这就是我现在所处的位置。:)

4

2 回答 2

52

关于如何从请求中获取凭据的问题的答案是这样的:

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

于 2010-03-10T01:26:50.483 回答
1

rails 插件Authlogic 开箱即用地支持此功能(以及更多功能)。您可以根植于它的源代码,或者简单地将其集成到您现有的应用程序中。

编辑:
在挖掘了 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

我会进一步了解这一切的去向,但我必须上床睡觉。希望我能有所帮助。

于 2010-03-08T06:01:08.893 回答