我想在我的第二个实例(我将称为Laravel API客户端)之前使用我的第一个Laravel实例的API路由(我将称为Laravel API提供者)。
Laravel API提供者基于vue / vuex / vue-router,并且API路由受laravel/passport
保护。
[[Laravel API提供程序]上受保护路由的一个示例:]/*Categories Routes*/
Route::group(['prefix' => 'categories'], function ($router) {
/*Index*/
Route::middleware('auth:api')->get('/', 'CategoriesApiController@index')
->name('api.categories.index');
});
所以现在我在上创建了此调用:Laravel API客户端
$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);
此返回:
{
"token_type": "Bearer",
"expires_in": 31622400,
"access_token": "eyJ0eXAiOiJKV1QiLC......",
"refresh_token": "def5020084262c0659e6f916b4da2c33e2a78de2206d......"
}
似乎不错。所以我的下一个问题是:如何在上使用Laravel API客户端
/api/categories/index
调用受保护的路由(例如$response
)?我想在我的第二个实例(我称为此Laravel API客户端)上使用我的第一个Laravel实例(我将称为Laravel API提供程序)的API-Routes。 Laravel API提供程序基于...Authorization
标头中设置的。令牌应在令牌前面具有'Bearer '
。因此,您可以通过以下方式实现此目标。$token = $response['access_token'];
$http= new Client();
$response = $http->request('GET', 'https://laravel-api-provider.local/api/categories/index', [
'headers' => [
'Authorization' => 'Bearer ' . $token,
],
]);