Thursday, March 16, 2017

Custom Header not available in Laravel $request object

I have a web application, where I am authenticating based on my custom token sent in headers as 'API_TOKEN'. I am not sure about what is happening, after all the code digging I did in source (laravel)

Here is my middleware

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;
}

Here is a screenshot of my POST request, api.easyinventory.com is a custom virtual host which maps to my app

enter image description here

My routes are placed right as follow in api.php which by default will placed below route group under api prefix

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

Coming to the problem, if I call getallheaders(), I can see my custom header as shown below

enter image description here

But in $request, I am not able to get it. I will be grateful for any lead on this issue.

My effort includes tracking down where these headers are actually SET in $request object, I checked ServerBag.php in Symfony source code

Symfony ServerBag Class Method - getHeaders.

If you look at this function getHeaders. It only adds selective headers in headers array, either with Content as starting string or starting with HTTP_. I tried passing my own header like HTTP_API_TOKEN but success :-(



via Farooq Khan

Advertisement