2010-06-03 159 views
0

我試圖讓我的Rails應用程序工作的基本http身份驗證。我提供了一個由Rails服務器提供的簡單REST接口,只有xml/json輸出。Rails 2.x http基本身份驗證

每一個方法需要進行認證的,所以我把在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.

回答

1

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

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

是否有反正我可以在用戶不提供登錄名/密碼對的情況下顯示一個XML生成器視圖?我想給出一個描述性的錯誤信息。 – randombits 2010-06-03 03:01:23

0

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