【问题标题】:Rails: Accessing the username/password used for HTTP Basic Auth?Rails:访问用于 HTTP 基本身份验证的用户名/密码?
【发布时间】:2011-01-24 20:41:30
【问题描述】:

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

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

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

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

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

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

【问题讨论】:

    标签: ruby-on-rails http-authentication


    【解决方案1】:

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

    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

    【讨论】:

    • 这是一个非常有帮助的答案 - 阅读起来似乎很简单,但我想知道如何做到这一点。感谢发帖。
    【解决方案2】:

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

    编辑:
    在挖掘了 Authlogic 的源代码后,我找到了this file,它使用以下代码来获取用户名和密码:

      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
    

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

    【讨论】:

      猜你喜欢
      • 2015-01-17
      • 2016-09-14
      • 1970-01-01
      • 1970-01-01
      • 2014-05-10
      • 2021-02-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多