【问题标题】:Use Laravel API by another (external) Laravel project另一个(外部)Laravel 项目使用 Laravel API
【发布时间】:2019-12-14 20:37:56
【问题描述】:

我想通过我的第二个实例(我将调用这个 Laravel API 客户端)使用我的第一个 Laravel 实例(我将称之为 Laravel API 提供者)的 API-Routes em>)。

Laravel API 提供者基于 vue/vuex/vue-router,API-routes 受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' => 'test@example.org',
                'password' => 'password',
            ],
        ]);

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

这会返回:

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

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

【问题讨论】:

    标签: laravel laravel-5 laravel-6


    【解决方案1】:

    Passport 使用不记名令牌,这是在 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,
        ],
    ]);
    

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

    【讨论】:

    猜你喜欢
    • 2021-06-19
    • 2020-01-08
    • 1970-01-01
    • 2021-03-04
    • 1970-01-01
    • 2014-07-03
    • 2018-07-22
    • 2020-07-30
    • 2017-01-26
    相关资源
    最近更新 更多