安装
composer require laravel/passport
执行数据库迁移
php artisan migrate
生成访问令牌所需的密钥
php artisan passport:keys
创建密码授权客户端
php artisan passport:client --password
配置
# 发布配置文件
php artisan vendor:publish --tag=passport-config
.env
文件中添加以下字段,值在 oauth_clients
表中
PASSPORT_PERSONAL_ACCESS_CLIENT_ID=
PASSPORT_PERSONAL_ACCESS_CLIENT_SECRET=
模型中 use HasApiTokens
use Laravel\Passport\HasApiTokens;
class User extends Authenticatable
{
use HasApiTokens;
}
注册路由
AuthServiceProvider
的 boot
方法中调用 Passport::routes()
修改配置
config/auth.php
中授权看守器 guards
的 api
的 driver
选项改为 passport
获取令牌
前后端分离使用密码授权令牌
- client_id: 客户端id,在
oauth_clients
表中 - client_secret: 客户端秘钥,在
oauth_clients
表中
$http = new GuzzleHttp\Client;
$response = $http->post('http://your-app.com/oauth/token', [
'form_params' => [
'grant_type' => 'password',
'client_id' => config('passport.personal_access_client.id'),
'client_secret' => config('passport.personal_access_client.secret'),
'username' => 'taylor@laravel.com',
'password' => 'my-password',
'scope' => '',
],
]);
return json_decode((string)$response->getBody(), true);
或者直接请求 http://your-app.com/oauth/token
,传递的 json
如下
{
"grant_type": "password",
"client_id": "client-id",
"client_secret": "client-secret",
"username": "taylor@laravel.com",
"password": "my-password",
"scope": "",
}
刷新令牌
- client_id: 同上
- client_secret: 同上
- refresh_token: 上面接口返回的
refresh_token
$http = new GuzzleHttp\Client;
$response = $http->post('http://your-app.com/oauth/token', [
'form_params' => [
'grant_type' => 'refresh_token',
'refresh_token' => 'the-refresh-token',
'client_id' => 'client-id',
'client_secret' => 'client-secret',
'scope' => '',
],
]);
return json_decode((string) $response->getBody(), true);
或者直接请求http://your-app.com/oauth/token
,传递的json
如下
{
"grant_type" => "refresh_token",
"refresh_token" => "the-refresh-token",
"client_id" => "client-id",
"client_secret" => "client-secret",
"scope" => "",
}