Laravel——Passport OAuth
安裝
在開始之前,請通過 Composer 包管理器安裝 Passport:
composer require laravel/passport 復(fù)制代碼Passport 服務(wù)提供器使用框架注冊自己的數(shù)據(jù)庫遷移目錄,因此在注冊提供器后,就應(yīng)該運行 Passport 的遷移命令來自動創(chuàng)建存儲客戶端和令牌的數(shù)據(jù)表:
php artisan migrate 復(fù)制代碼接下來,運行 passport:install 命令來創(chuàng)建生成安全訪問令牌時所需的加密密鑰,同時,這條命令也會創(chuàng)建用于生成訪問令牌的「個人訪問」客戶端和「密碼授權(quán)」客戶端:
php artisan passport:install 復(fù)制代碼配置
上面命令執(zhí)行后,請將 Laravel\Passport\HasApiTokens Trait 添加到 User 模型中, 這個 Trait 會給你的模型提供一些輔助函數(shù),用于檢查已認(rèn)證用戶的令牌和使用范圍:
Models/User.php
class User extends Authenticatable {use HasApiTokens, Notifiable; } 復(fù)制代碼在 AuthServiceProvider 的 boot 方法中調(diào)用 Passport::routes 函數(shù)。這個函數(shù)會注冊發(fā)出訪問令牌并撤銷訪問令牌、客戶端和個人訪問令牌所必需的路由:
Provinders/AuthServiceProvider.php
public function boot() {$this->registerPolicies();Passport::routes();//設(shè)置token過期時間Passport::tokensExpireIn(now()->addDays(1)); //設(shè)置刷新token過期時間Passport::refreshTokensExpireIn(now()->addDays(30)); } 復(fù)制代碼將配置文件 config/auth.php 中授權(quán)看守器 guards 的 api 的 driver 選項改為 passport。此調(diào)整會讓你的應(yīng)用程序在在驗證傳入的 API 的請求時使用 Passport 的 TokenGuard 來處理:
config/auth.php
'guards' => ['web' => ['driver' => 'session','provider' => 'users',],'api' => ['driver' => 'passport','provider' => 'users','hash' => false,],], 復(fù)制代碼密碼模式
在應(yīng)用程序通過密碼授權(quán)機制來發(fā)布令牌之前,在 passport:client 命令后加上 --password 參數(shù)來創(chuàng)建密碼授權(quán)的客戶端。如果你已經(jīng)運行了 passport:install 命令,則不需要再運行此命令:
php artisan passport:client --password
請求令牌
創(chuàng)建密碼授權(quán)的客戶端后,就可以使用用戶的電子郵件地址和密碼向 /oauth/token 路由發(fā)出 POST 請求來獲取訪問令牌。而該路由已經(jīng)由 Passport::routes 方法注冊,因此不需要手動定義它。如果請求成功,會在服務(wù)端返回的 JSON 響應(yīng)中收到一個 access_token 和 refresh_token:
請求參數(shù):
'grant_type' => 'password', 'client_id' => 'client-id', //需要使用password_client=1 'client_secret' => 'client-secret', 'username' => 'taylor@laravel.com', 'password' => 'my-password', 'scope' => '', 復(fù)制代碼自定義用戶名字段
當(dāng)使用密碼授權(quán)時,Passport 默認(rèn)使用 email 作為「用戶名」。但是,你可以通過在模型上定義一個 findForPassport 方法來自定義用戶名字段:
Models/User.php
/*** 通過用戶名找到對應(yīng)的用戶信息** @param string $username* @return \App\User*/ public function findForPassport($username) {return $this->where('username', $username)->first(); } 復(fù)制代碼路由保護(hù)
通過中間件
Passport 包含一個 驗證保護(hù)機制 可以驗證請求中傳入的訪問令牌。配置 api 的看守器使用 passport 驅(qū)動程序后,只需要在需要有效訪問令牌的任何路由上指定 auth:api 中間件:
Route::middleware('auth:api')->group(function () {}); 復(fù)制代碼參考文檔
Laravel5.8
轉(zhuǎn)載于:https://juejin.im/post/5cb7d643518825186d654246
總結(jié)
以上是生活随笔為你收集整理的Laravel——Passport OAuth的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Codeforces Round #55
- 下一篇: [LeetCode][JavaScrip