4

我有一個使用令牌來驗證用戶的rails應用程序。目前我正在傳遞令牌作爲params。我想改變這一點。我相信它可以通過html頭傳遞它。我不知道如何使用authenticate_or_request_with_http_token do |token, options|。 我的Rails應用程序實際上是我的iPhone客戶端的服務器。我的東西我不明白是:通過http頭傳遞真實性令牌

  1. 我知道options是隨機數,但如何將我的客戶端和服務器之間的工作呢?

  2. 我該如何在服務器代碼中實際使用它?

  3. 我可以使用authenticate_or_request_with_http_token do |token, options|檢查標頭中的標記,但是如何在成功創建會話後將其插入到標頭中。

這裏是我的服務器會話控制器:

def create 
if @user && @user.authenticate(params[:password]) 
# @token = @user.auth_token 
@user.auth_token = SecureRandom.hex 
@user.save 
    respond_to do |format| 
     format.json {render :json => {:status => "200", :message => "Logged in successfully", :auth_token => @user.auth_token}} 
    end 
else 
    respond_to do |format| 
     format.json {render :json => {:status => "401", :message => "wrong credentials"}} 
    end 
end 
    end 

    def destroy 
    if(@user) 
     @user.auth_token = "" 
     @user.save 
     respond_to do |format| 
     format.json {render :json => {:status => "200", :message => "logged out successfully"}} 
     end 
    else 
     respond_to do |format| 
     format.json {render :json => {:status => "401", :message => "No User"}} 
     end 
    end 
    end 

def user 
    @user = User.find_by_auth_token(params[:auth_token]) 
end 
+0

設置你使用'response.headers'的自定義頭文件,就像'response.headers [「X-AUTH-TOKEN」] = auth_token'應該可以工作..讀取你使用'request.headers [「X -AUTH-TOKEN「]' – Orlando

+1

這個作品,謝謝。如果您將它作爲答案發布,我會接受它:) – nupac

回答

4

設置使用response.headers自定義標頭。

喜歡的東西

response.headers["X-AUTH-TOKEN"] = auth_token 

應該工作..閱讀使用

request.headers["X-AUTH-TOKEN"] 

X-在命名的頭是一個很好的做法慣例,所有的自定義標題應該在前面的X-

+1

不推薦使用X-。 –

+0

@ m.samy我認爲你是對的,來源(http://tools.ietf.org/html/draft-ietf-appsawg-xdash-02),但看起來像一個草案..你知道,如果該文件被接受了? – Orlando

+1

關於X-前綴與無前綴的更多討論:http://stackoverflow.com/questions/3561381/custom-http-headers-naming-conventions – dmur