2017-03-16 74 views
1

我有一個web應用程序,我正在基於自定義令牌進行身份驗證,這些自定義令牌在標頭中發送爲'API_TOKEN'。我不知道發生了什麼,畢竟代碼挖我在源做(laravel)

這裏是我的中間件

protected $AUTH_HEADER = 'API_TOKEN'; 
protected $_RESPONSE = array('status' => false, 'message' => '', 'data' => array()); 

public function handle($request, Closure $next, $guard = null) 
{ 
    $response = $this->_RESPONSE; 
    if($request->hasHeader($this->AUTH_HEADER)){ 
    $api_token = $request->header($this->AUTH_HEADER); 
    try{ 
     $request->user = \App\User::where(['api_token' => $api_token])->firstOrFail(); 
     Auth::login($request->user); 
     $response = $next($request); 
    }catch(\Exception $exception){ 
     $response['status'] = false; 
     $response['message'] = 'Invalid Token.'; 
    } 
    }else{ 
    $response['status'] = false; 
    $response['message'] = 'Unauthorized Request.'; 
    } 

    // Lines ONLY I used for cross verification of availability of my header 
    // $response['data'] = getallheaders(); 
    // $response['data'] = $_SERVER; 
    return $response; 
} 

這裏是我的POST請求的截圖,api.easyinventory.com是一個自定義的虛擬主機映射到我的應用程序

enter image description here

我的路線被放置如右圖按照api.php,默認會在下面放置航線組下api前綴

Route::group(['prefix' => 'product'], function(){ 
    Route::get('read', 'API\[email protected]'); 
} 

來到這個問題,如果我叫getallheaders(),我可以看到我的自定義頁眉如下圖所示

enter image description here

但在$request,我沒有能夠得到它。我將非常感謝在這個問題上的任何領導。

我的努力,包括跟蹤,其中這些標題實際上是SET$request對象,我在Symfony的源代碼

Symfony ServerBag Class Method - getHeaders檢查ServerBag.php

如果你看看這個功能getHeaders。它僅在headers數組中添加選擇性標題,可以使用Content作爲起始字符串或從HTTP_開始。我想通過我自己的頭就像HTTP_API_TOKEN但成功:-(

+0

你只是想使用'api_token'對用戶進行認證? – EddyTheDove

+0

其實是的,但我問題是關於訪問'$ request'對象中的自定義標頭值 –

+0

噢,你只是試圖訪問自定義標頭,我以爲你正在嘗試認證,因爲laravel具有api_token的開箱驗證功能。你想要什麼... – EddyTheDove

回答

0

你能與全球幫手嘗試request()

request()->header('API_TOKEN'); //<-- manually passing the string first, for test purposes 
+0

不幸的是,它不工作k –

+0

我這麼傻,原來是個小問題。我們應該以'Camel cased'的形式訪問我們的頭文件,因此在中間件中將它作爲'API-TOKEN'發送並作爲'Api-Token'訪問。 o__0 –

+1

很高興你解決了它。 – EddyTheDove