由另一个(外部)Laravel项目使用Laravel API

问题描述 投票:2回答:1

我想在我的第二个实例(我将称为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提供程序基于...
laravel laravel-5 laravel-6
1个回答
0
投票
护照使用不记名令牌,这是在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, ], ]);

© www.soinside.com 2019 - 2024. All rights reserved.