自定义标题在Laravel $请求对象中不可用

问题描述:

我有一个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

你能与全球帮手尝试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