安裝
composer require laravel/passport
運行遷移
php artisan migrate
創建訪問令牌
- [個人訪問] 客戶端和 [密碼授權] 客戶端
php artisan passport:install
- 單獨創建 密碼授權 客戶端
php artisan passport:client --password
- 單獨創建 個人訪問 客戶端
php artisan passport:client --client
模型中使用
在模型中加入 HasApiTokens Trait
class User extends Authenticatable
{
use HasApiTokens, Notifiable;
}
生成 Passport 生成訪問令牌所需的祕鑰(大白話:每生成一個令牌都要使用到它)
生成的祕鑰一般情況不應放在版本控制中,默認生成的文件存放在 storage 目錄下
php artisan passport:keys
令牌的有限期配置
在 AuthServiceProvider 中配置
public function boot()
{
$this->registerPolicies();
Passport::routes();
// 配置 令牌 失效時間
Passport::tokensExpireIn(now()->addDays(15));
// 配置 刷新令牌 失效時間
Passport::refreshTokensExpireIn(now()->addDays(30));
// 配置 個人訪問令牌 失效時間
Passport::personalAccessTokensExpireIn(now()->addMonths(6));
}
密碼授權方式獲取訪問令牌
http = new GuzzleHttp\Client;
$response = $http->post('http://your-app.com/oauth/token', [
'form_params' => [
'grant_type' => 'password',
'client_id' => 'client-id',
'client_secret' => 'client-secret',
'username' => '[email protected]',
'password' => 'my-password',
'scope' => '',
],
]);
return json_decode((string) $response->getBody(), true);
自定義登錄用戶名
在對應的 用戶(如 User、Admin) 模型中進行設置
<?php
namespace App;
use Laravel\Passport\HasApiTokens;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
use HasApiTokens, Notifiable;
/**
* 通過給定的username獲取用戶實例。
*
* @param string $username
* @return \App\User
*/
public function findForPassport($username)
{
return $this->where('username', $username)->first();
}
}
demo:https://github.com/ruitaoZhang/laravel-api-demo
多表認證相關及注意要點
1、passport中有 客戶端密碼授權、個人授權。
如果是要用到第三方授權登錄,可以使用 個人授權 Personal Token
- 密碼授權通過請求 /oauth/token 來獲取 access_token
- 個人授權可通過
$user->createToken ('name_string')->token
來獲取
2、attempt 方法
Passport 的 guard 並未實現 attempt 方法,所有當使用 Auth::attempt($credentials)
會報錯
3、多表用戶認證,得到的 access_token 可以通過其他表認證?
解決
首先在 app/Kernel
中的 $routeMiddleware
加入
'scopes' => \Laravel\Passport\Http\Middleware\CheckScopes::class,
'scope' => \Laravel\Passport\Http\Middleware\CheckForAnyScope::class,
在 AuthServiceProvider
中的 boot()
方法定義授權作用域(Scope)
public function boot()
{
$this->registerPolicies();
Passport::routes();
// 定義作用域
Passport::tokensCan([
'admin-api' => 'admin api',
'user-api' => 'user api',
]);
}
在獲取 token 時,指定對應的 作用域(Scope)
$user->createToken('Personal Access Token', ['user-api'])->token;
在認證路由中添加中間件
Route::group([
'middleware' => ['auth:api', 'scope:user-api']
], function () {
Route::post('userInfo', 'Api\AuthController@userInfo');
});
相應文檔地址:查看