Rails:访问用于HTTP Basic Auth的用户名/密码?

Shp*_*ord 20 ruby-on-rails http-authentication

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

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

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

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

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

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

der*_*red 50

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

user, pass = ActionController::HttpAuthentication::Basic::user_name_and_password(request)
Run Code Online (Sandbox Code Playgroud)

但是,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
Run Code Online (Sandbox Code Playgroud)

如果未提供凭据,authenticate_or_request_with_http_basic将返回401状态,这将在浏览器中弹出用户名/密码对话框.如果给出了详细信息,那么这些细节将传递给提供的块.如果块返回true,则请求通过.否则,请求处理被中止,并且403状态被返回给客户端.

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