laravel - 通过另一个(外部)Laravel 项目使用 Laravel API

标签 laravel laravel-5 laravel-6

我想通过我的第二个实例(我将调用此 Laravel API 客户端)使用第一个 Laravel 实例(我将调用此 Laravel API 提供程序)的 API 路由em>)。

Laravel API 提供程序基于 vue/vuex/vue-router,API 路由受 laravel/passport 保护。

Laravel API 提供者上 protected 路由的一个示例:

/*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' => '<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="364253454276534e575b465a5318594451" rel="noreferrer noopener nofollow">[email protected]</a>',
                'password' => 'password',
            ],
        ]);

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

这将返回:

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

看起来不错。所以我的下一个问题是:如何在我的 Laravel API 客户端上使用 $response 调用 protected 路由(例如 /api/categories/index) ?

最佳答案

Passport 使用不记名 token ,这是在 Authorization header 中设置的。 token 前面应有'Bearer '。所以你可以用这样的东西来实现它。

$token = $response['access_token'];

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

为了获得最佳使用效果,请存储 token ,并且当调用不再被授权时,使用刷新 token 来获取新 token 。但现在这应该会让你朝着正确的方向前进。

关于laravel - 通过另一个(外部)Laravel 项目使用 Laravel API,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59338949/

相关文章:

Laravel 数据库队列频率

Laravel 黄昏截图

php - 尝试在 laravel 上运行 gulp 时出现错误

mysql - Laravel 默认用户迁移

php - Laravel与Docker-Compose

php - 计算 laravel 5 中所有类别的帖子

javascript - 如何将 blade 变量传递给 vue 实例以便我可以在我的 JavaScript 文件中使用它?

unit-testing - 浏览器测试时是否多次调用缓存模拟?

php - Laravel 6.x 的次要版本是否考虑 LTS?

node.js - 'npm' 在 laravel 6.0 中不是内部或外部命令,也不是可运行的程序或批处理文件