簡體   English   中英

Rails 2.x HTTP基本認證

[英]Rails 2.x http basic authentication

我正在嘗試在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。

您必須指定一個登錄名/密碼對,即使您不檢查它們

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

如果要顯示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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM