2010-03-08 39 views
19

我正在構建一個基本的API,在用戶的登錄名和密碼被正確發送後,用戶信息可以被檢索。Rails:訪問用於HTTP Basic Auth的用戶名/密碼?

現在我使用的是這樣的:

http://foo:[email protected]/api/user.xml

所以,我需要做的是訪問的請求(foobar)發送的用戶/密碼,但我不知道如何在Rails控制器中訪問這些信息。

然後我會通過快速User.find檢查這些變量,然後將它們設置爲authenticate_or_request_with_http_basic的用戶名和密碼變量。

這可能是我以完全錯誤的方式看待這個問題,但這正是我現在所處的位置。 :)

回答

47

回答你的如何從請求的憑證問題是:

user, pass = ActionController::HttpAuthentication::Basic::user_name_and_password(request) 

然而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 

authenticate_or_request_with_http_basic將返回401狀態,如果沒有提供證書,將在瀏覽器中彈出用戶名/密碼對話框。如果給出了詳細信息,那麼將傳遞給提供的塊。如果該塊返回true,則請求會通過。否則,請求處理被中止,並將403狀態返回給客戶端。

您還可以檢查出Railscast 82(那是上面的代碼是從): http://railscasts.com/episodes/82-http-basic-authentication

+0

這是一個非常有用的答案 - 這看似簡單的閱讀這件事,但是我想知道如何做到這一點。感謝發佈。 – 2012-09-08 03:02:42

1

軌道插件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 

我還翻看了一下到一切都去了,但我必須去睡覺。希望我有一些幫助。

相關問題