Rails:访问用于 HTTP 基本身份验证的用户名/密码?

Rails:访问用于 HTTP 基本身份验证的用户名/密码?

问题描述:

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

I'm building a basic API where user information can be retrieved after that user's login and password are correctly sent.

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

Right now I'm using something like this:

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

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

So, what I need to do is access the user/password sent in the request (the foo and bar) but am not sure how to access that info in a Rails controller.

然后我会通过快速的 User.find 检查这些变量,然后将它们设置为 authenticate_or_request_with_http_basic 的用户名和密码变量.

Then I'd check those variables via a quick User.find and then set those as the username and password variables for authenticate_or_request_with_http_basic.

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

It's possible I'm looking at this at the completely wrong way, but that's where I'm at right now. :)

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

The answer to your question of how to get the credentials from the request is this:

user, pass = ActionController::HttpAuthentication::Basic::user_name_and_password(request)

但是,authenticate_or_request_with_http_basic 是您进行基本身份验证所需的全部内容:

However authenticate_or_request_with_http_basic is all you need to do basic auth:

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 状态.

authenticate_or_request_with_http_basic will return a 401 status if credentials are not supplied, which will pop up the username/password dialog in a browser. If details are given then those are passed to the block provided. If the block returns true the request goes through. Otherwise the request processing is aborted and a 403 status is returned to the client.

您还可以查看 Railscast 82(上面的代码来自):http://railscasts.com/episodes/82-http-basic-authentication

You can also check out Railscast 82 (thats were the code above is from): http://railscasts.com/episodes/82-http-basic-authentication