【问题标题】:Rails 2.x http basic authenticationRails 2.x http 基本认证
【发布时间】:2010-06-03 02:45:27
【问题描述】:

我正在尝试在我的 Rails 应用程序上使用基本的 http 身份验证。我提供了一个由 Rails 服务器提供的简单 REST 接口,只有 xml/json 输出。

每个方法都需要认证,所以我把认证过滤器放在ApplicationController中:

class ApplicationController < ActionController::Base
  helper :all # include all helpers, all the time
  before_filter :authenticate

protected
  def authenticate
    authenticate_or_request_with_http_basic do |u, p|
      true
    end
  end
end

即使该方法返回 true,我仍会收到来自服务器的 401:

$ curl http://127.0.0.1:3000/myresource/1.xml -i
HTTP/1.1 401 Unauthorized 
Cache-Control: no-cache
WWW-Authenticate: Basic realm="Application"
X-Runtime: 1
Content-Type: text/html; charset=utf-8
Content-Length: 27
Server: WEBrick/1.3.1 (Ruby/1.9.1/2010-01-10)
Date: Thu, 03 Jun 2010 02:43:55 GMT
Connection: Keep-Alive

HTTP Basic: Access denied.

如果我明确返回 true,但得到的是 401。

【问题讨论】:

    标签: ruby-on-rails ruby authentication


    【解决方案1】:

    您必须指定登录名/密码对,即使您不检查它们

    curl http://127.0.0.1:3000/myresource/1.xml -i -u username:password
    

    【讨论】:

    • 如果用户不提供登录名/密码对,我是否可以显示 xml 构建器视图?我想给出一个描述性的错误信息。
    【解决方案2】:

    如果您想为 XML 请求显示错误消息,您可以编写自己的 before_filter

    class ApplicationController < ApplicationController::Base
      before_filter :authenticate
    
      def authenticate
        authentication_procedure = lambda do |username, password|
          # test username and password
        end
        authenticate_with_http_basic(&authentication_procedure) ||
          request_http_basic_authentication_or_show_xml_error(&authentication_procedure)
      end
    
      def request_http_basic_authentication_or_show_xml_error(&auth_proc)
        if request.format == Mime::XML
          render :action => '/errors/401'
        else
          request_http_basic_authentication('My Realm')
        end
      end
    end
    

    然后把东西放到app/views/errors/401.xml.builder

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-07-27
      • 2012-01-06
      • 2012-01-02
      • 2011-05-06
      • 1970-01-01
      • 2011-05-03
      • 2012-01-09
      相关资源
      最近更新 更多