- 安裝conposer擴充
composer require laravel/passport
- 生成passport配置檔案
<?php
return [
'scopes' => [
'place-orders' => 'Place orders',
'check-status' => 'Check order status',
'*' => 'all scopes',
],
'default' => [
'client_id' => env('CLIENT_ID'),
'client_secret' => env('CLIENT_SECRET'),
'scope' => '*',
],
// 訪問令牌有效期(天)
'tokensExpireIn' => 15,
// 重新整理後的訪問令牌有效期(天)
'refreshTokensExpireIn' => 30,
];
- 執行migrate命令生成表
php artisan migrate
- 生成訪問祕鑰
php artisan passport:install
- 在模型中新增引用
use HasApiTokens, Notifiable;
- 在Providers/AuthServiceProvider中的boot方法中新增訪問路由
public function boot()
{
$this->registerPolicies();
//註冊發出訪問令牌並撤銷訪問令牌、客戶端和個人訪問令牌所必需的路由
Passport::routes();
// 定義令牌作用域
Passport::tokensCan(config('passport.scopes'));
// 訪問令牌有效期(天)
Passport::tokensExpireIn(now()->addDays(15));
// 重新整理後的訪問令牌有效期(天)
Passport::refreshTokensExpireIn(now()->addDays(30));
}
- 在config/auth.php中設定驅動
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'api' => [
'driver' => 'passport',
'provider' => 'users',
],
],
'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => App\Models\Login::class,
],
- 請求獲取token
public function getToken($username, $password)
{
$data = [
'username' => $username,
'password' => $password,
'scope' => config('passport.default.scope'),
'client_id' => config('passport.default.client_id'),
'client_secret' => config('passport.default.client_secret'),
'grant_type' = 'password'
];
$http = new Client();
try {
$result = $http->post(url('/oauth/token'), [
'form_params' => $data,
]);
} catch (\Exception $e) {
\Log::error('申請密碼令牌失敗:欄位資訊為:' . json_encode($data) . '錯誤:' . $e->getMessage());
$error = explode("\n", $e->getMessage())[1];
if ($error[strlen($error) - 1] != '}') {
$error = $error . '"}';
}
if (empty(json_decode($error))) return ['success' => false, 'message' => '伺服器異常,請聯絡管理員'];
switch (json_decode($error)->error) {
case 'invalid_grant':
$errorMessage = '使用者名稱或密碼錯誤!';
break;
case 'invalid_client':
case 'invalid_request':
$errorMessage = '客戶端出錯,請重新下載!';
break;
default:
$errorMessage = '未知錯誤,請聯絡管理員!';
break;
}
return ['success' => false, 'message' => $errorMessage];
}
$token = json_decode((string)$result->getBody(), true)['access_token'];
return ['status' => true, 'token' => $token];
}
- 更改登入欄位
在使用者模型新增
// 自定義授權使用者名稱(預設為登入賬號)
public function findForPassport($username)
{
return Admin::where('tel', $username)->first();
// 也可以使用多欄位登入
return Admin::where('tel', $username)->orWhere('name', $username)->first();
}
- 如果你的使用者表是使用的guid
請使用migrate檔案修改 possport 表欄位, 在之前,請安裝 doctrine/dbal 擴充
本作品採用《CC 協議》,轉載必須註明作者和本文連結