配置Passport

1.首先使用composer安装passport

composer require laravel/passport

2.注册服务提供者

进入config/app.php中,将下面行添加到providers数组中

/*
 * Package Service Providers...
 */
 Laravel\Passport\PassportServiceProvider::class,

3.在App\User模型中的use后面添加HasApiTokens

class User extends Authenticatable
{
    use HasApiTokens, Notifiable;
}

4.在AuthServiceProviderboot方法中调用

// 配置passport路由
Passport::routes();
// 或者使用下面这行给URI添加前辍
//Passport::routes(null,['prefix'=>'api/oauth']);

// token的有效期时长:2小时
Passport::tokensExpireIn(Carbon::now()->addHour(2));

// refresh token的有效期时长:7天
Passport::refreshTokensExpireIn(Carbon::now()->addDay(7));

5.将config/auth.php的配置文件的guards/api/driver修改为passport

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

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

6.在服务器中执行数据填充

php artisan migrate

7.生成密钥

php artisan passport:install

执行上述命令会生成类似的密钥

Personal access client created successfully.
Client ID: 1
Client Secret: Fo6GS5UyNuCIeZtBhIUzA9W99sonUoZNo26Zi67t
Password grant client created successfully.
Client ID: 2
Client Secret: kCvv28qy25rIw5IYvAwpIHNQvBMnH6FElrzxqvqP

简单的配置就些完成。

测试上述配置

打开Postman或者类似的工具

  • 方法为POST

  • 链接为http://你的域名/oauth/token,(假如你使用了URI的前辍,则要在你的URI前加上你自定义的那个前辍)

  • 在表单数据中添加以下项

key value
client_id 这里使用的是生成密钥里的clientid值
client_secret 这个是上面ID对应的secret
username users表里用于登录的用户名,默认为邮箱,除非你修改过默认值
password 用户登录对应的密码
grant_type password(oauth2有多种类型,我这里使用密码验证类型测试)

下面附一个演示的数据,不要照抄,只作参考

key value
client_id 2
client_secret kCvv28qy25rIw5IYvAwpIHNQvBMnH6FElrzxqvqP
username aaa@test.com
password 123456
grant_type password

填好上面内容后,点Send,服务器返回一个json数据就表示Passport配置成功了

{
    "token_type": "Bearer",
    "expires_in": 7200,
    "access_token": "eyJ0eXAiOiJKV1QiLCJhbGciO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oVALojqsMaNfM",
    "refresh_token": "def50200344953b3f39ad35917ff6981ae428f3b48705899e6218149701d7ee3cd419c8297961603444f8ea9174154baa6a04740ee8d2e58403999c92e567f0c5ebdde0ebde6ebc965bc91a1d5c8d012cb7f0b159226e187d5500458c41a6feb4fc9908f9ab9b43f5c9eb82d8e0507fd3db92e6253990acbf9edb6f1b8b3e857c559e23b015af0331ace28d63df4d25e62a8538565e52f38579f6a57582f3446fa2855ff86c7a9ee401671fd70f3a151eb97d1b83abd09612d8d1ccc93c35b64585a051fef2fc971286f135ed5f7e66858c169a2f05192c85458557c5dd2d21b015b43a3d409914cc9e4f719abb8e9376d88d4cee295a25a32bed45f60ddba6f3679980a40604ac563601442e549557cc3d0c2e9b8c722b414b87875180472d66675b1902124a7502123eb2feee87131243eb06c1ea72c11c8ff5b7c65f35544a9e35bde1fe74c99ec6cb1d16a4ec68fec046f3637737ef18f5998b9368c5190f7"
}

图片描述


Chiu
312 声望5 粉丝