2

I would like to use the API-Routes of my first Laravel instance (I will call this Laravel API provider) by my second instance (I will call this Laravel API client).

The Laravel API provider is based on vue/vuex/vue-router and the API-routes are protected by laravel/passport.

One example for a protected route on the Laravel API provider:

/*Categories Routes*/
Route::group(['prefix' => 'categories'], function ($router) {

    /*Index*/
    Route::middleware('auth:api')->get('/', 'CategoriesApiController@index')
        ->name('api.categories.index');
});

So now I created this call on my Laravel API client:

 $http= new Client();
        $response = $http->request('POST', 'https://laravel-api-provider.local/oauth/token', [
            'headers' => [
                'cache-control' => 'no-cache',
                'Content-Type' => 'application/x-www-form-urlencoded'
            ],
            'form_params' => [
                'client_id' => '2',
                'client_secret' => 'secret',
                'grant_type' => 'password',
                'username' => '[email protected]',
                'password' => 'password',
            ],
        ]);

        return json_decode((string) $response->getBody(), true);

This returns:

{
  "token_type": "Bearer",
  "expires_in": 31622400,
  "access_token": "eyJ0eXAiOiJKV1QiLC......",
  "refresh_token": "def5020084262c0659e6f916b4da2c33e2a78de2206d......"
}

Seems good. So my next question is: How do I call protected routes (like /api/categories/index) using $response on my Laravel API client?

1 Answer 1

2

Passport uses bearer tokens, this is set in the Authorization header. The token should have 'Bearer ' in front of the token. So you could achieve it with something like this.

$token = $response['access_token'];

$http= new Client();
$response = $http->request('GET', 'https://laravel-api-provider.local/api/categories/index', [
    'headers' => [
        'Authorization' => 'Bearer ' . $token,
    ],
]);

For most optimal usage, store the token and when the calls is not authorized anymore use the refresh token to get a new one. But for now this should get you going in the right direction.

Sign up to request clarification or add additional context in comments.

1 Comment

Another way is to use laravel.com/docs/8.x/http-client since v7

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.