I'm using Laravel Dingo to consume API requests (internally) within Laravel controllers, and have come up against a problem with routes which are authenticated with tokens in headers. I'm getting an Exception thrown, looking for a token in requests.
This is my API routes:
$api = app('Dingo\Api\Routing\Router');
$api->version(['v1'], function ($api) {
$api->post('/users/addEmployee', "App\Http\Controllers\Api\UserController@storeEmployee")->middleware('jwt.auth');
}
Note the middleware added to the call. When using Postman, this works 100% and adds a new employee.
When calling it internal with Dingo, I get back the typical 'token not found' error that I would typically see from the API when the Authorisation Header is missing.
try{
$dispatcher = app('Dingo\Api\Dispatcher');
$payload = [
'name' => $request->name,
'email' => $request->email,
];
$registerResponse = $dispatcher->be(Auth::user())->with($payload)->post('/api/users/addEmployee');
catch( InternalHttpException $internal ){
echo($internal->getResponse());die();
return Redirect::back()->withInput()->withErrors($v->getErrors());
}
My question is this, do I need to add the token, or is there a way to 'turn off' jwt middleware for an internal request? Does the ->be method not handle all of this within Dingo? p.s. Auth::user is not null, I've checked that.
Solved it, you can manually set headers on outbound requests prior to it being dispatched. Didn't see the method anywhere in the docs, but following works.
$token = JWTAuth::fromUser(Auth::user());
$registerResponse = $this->api->header('Authorization','Bearer:'.$token)->with($payload)->be(Auth::user())->post('/api/users/addEmployee');