Search code examples
laravellaravel-passport

Calling api route from job with auth:api middleware internally


I'm using laravel passport's auth:api middleware to authenticate my api routes which requires a bearer token to authenticate. I use queued jobs for a variety of tasks for my application, some of this jobs call out to these api roots. An example of a job is as followed.

public function handle()
{
    $this->data['foreign_id'] = (string) Str::uuid();

    $activity = new Activity($this->data);

    $activity->save();

    ApiClient::postToApi('/feeds/activity', $this->data);
}

The api client code is used to handle internal requests inside the application. The code can be seen below

public function postToApi($url, $data) {
    $req = Request::create($url, 'POST', $data);

    $req->headers->set('Authorization', 'Bearer '. $this->grabToken());
    $req->headers->set('Accept', 'application/json');


    try {
        $res = app()->handle($req);
        return $res;
    } catch (Exception $e) {
        return "not found";
    }
}

This request creates a request with a bearer token that is generated using the currently logged in user so that the request can be authenticated

               $token = $user->createToken('Token Name')->accessToken;

However because this call was sent out by a job I don't have access to the sessions user, this means that no bearer token can be generated and I get an unauthenticated message. Is there anyway to get around this or this there a way I can bypass the middleware when completing internal requests? Thanks.


Solution