自定义标题在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
是一个自定义的虚拟主机映射到我的应用程序
我的路线被放置如右图按照api.php
,默认会在下面放置航线组下api
前缀
Route::group(['prefix' => 'product'], function(){
Route::get('read', 'API\[email protected]');
}
来到这个问题,如果我叫getallheaders()
,我可以看到我的自定义页眉如下图所示
但在$request
,我没有能够得到它。我将非常感谢在这个问题上的任何领导。
我的努力,包括跟踪,其中这些标题实际上是SET
在$request
对象,我在Symfony的源代码
Symfony ServerBag Class Method - getHeaders检查ServerBag.php
。
如果你看看这个功能getHeaders
。它仅在headers
数组中添加选择性标题,可以使用Content
作为起始字符串或从HTTP_
开始。我想通过我自己的头就像HTTP_API_TOKEN
但成功:-(
你能与全球帮手尝试request()
request()->header('API_TOKEN'); //<-- manually passing the string first, for test purposes
不幸的是,它不工作k –
我这么傻,原来是个小问题。我们应该以'Camel cased'的形式访问我们的头文件,因此在中间件中将它作为'API-TOKEN'发送并作为'Api-Token'访问。 o__0 –
很高兴你解决了它。 – EddyTheDove
你只是想使用'api_token'对用户进行认证? – EddyTheDove
其实是的,但我问题是关于访问'$ request'对象中的自定义标头值 –
噢,你只是试图访问自定义标头,我以为你正在尝试认证,因为laravel具有api_token的开箱验证功能。你想要什么... – EddyTheDove