laravel 使用guzzlehttp/guzzle 配置步驟

helong3314發表於2021-06-17

1、安裝guzzlehttp/guzzle

透過 Composer 包管理器安裝 guzzlehttp/guzzle

composer require guzzlehttp/guzzle

2、安裝laravel/passport

透過 Composer 包管理器安裝 Passport

composer require laravel/passport

3、配置config/auth.php

3、1 修改看守器
修改之前

'guards'  => [

'web'  => [

'driver'  =>  'session',

'provider'  =>  'users',

],

'api'  => [

'driver'  =>  'token',

'provider'  =>  'users',

'hash'  =>  false,

],

],

修改之後

'guards'  => [

'web'  => [

'driver'  =>  'session',

'provider'  =>  'users',

],

'api'  => [

'driver'  =>  'passport',

'provider'  =>  'users',

'hash'  =>  false,

],

],

3、2 新增app\Providers\AuthServiceProvider
修改之前

public  function  boot()

{

$this->registerPolicies();
}

修改之後

public  function  boot()

{

$this->registerPolicies();

//passport 註冊發出訪問令牌並撤銷訪問令牌、客戶端和個人訪問令牌所必需的路由

Passport::routes();

//令牌有效期

Passport::tokensExpireIn(now()->addDays(15));

//重新整理令牌的令牌有效期

Passport::refreshTokensExpireIn(now()->addDays(30));

//個人令牌有效期

Passport::personalAccessTokensExpireIn(now()->addMonths(6));

}

3、3 模型配置

use  Illuminate\Database\Eloquent\Factories\HasFactory;

use  Laravel\Passport\HasApiTokens;

use  Modules\Common\Entities\Authenticatable;

use  Spatie\Permission\Traits\HasRoles;

class  User  extends  Authenticatable

{

use  HasFactory;

use  HasApiTokens;

use  HasRoles;

use  HasFactory;
}

4、安裝

php artisan passport:install

生成記錄存放在資料表 oauth_clients

5、oauth/token 請求

Route::get('/auth/callback', function (Request $request) {
    $http = new GuzzleHttp\Client;

    $response = $http->post('http://laravel55.dev/oauth/token', [
        'form_params' => [
            'grant_type' => 'authorization_code',
            'client_id' => '2',  // oauth_clients 的ID 
            'client_secret' => 'tBxbskNg9fJTIh0Ufk4eKdpneSkLx1H5HxGy2VTk',   // oauth_clients secret
            'redirect_uri' => 'http://laravel55.dev/auth/callback',
            'code' => $request->code,
        ],
    ]);

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

注意:password_client欄位值必須是1,provider的值是看守器,必須對於 config/auth.php 檔案guards =》【web=》provider】的值

'guards' => [
    'web' => [
        'provider' => 'users',
    ],

    'api' => [
        'provider' => 'users',
    ],
],

passport:client命令

建立客戶端最簡單的方式就是使用 Artisan 命令 passport:client,該命令可用於建立你自己的客戶端以方便測試 OAuth2 功能。當你執行 client 命令時,Passport 會提示你輸入更多關於客戶端的資訊,並且為你生成 client ID 和 secret

php artisan passport:client

laravel 使用guzzlehttp/guzzle 配置步驟

laravel 使用guzzlehttp/guzzle 配置步驟

本作品採用《CC 協議》,轉載必須註明作者和本文連結

相關文章