1. 安装 jwt-auth
composer require php-open-source-saver/jwt-auth
2. 设置 jwt secret
php artisan jwt:secret
3. 修改 config/auth.php
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
// 增加这四行
'api' => [
'driver' => 'jwt',
'provider' => 'users',
],
],
4. 修改 app\Models\User.php
<?php
...
// 增加这行
use PHPOpenSourceSaver\JWTAuth\Contracts\JWTSubject;
// 增加 implements JWTSubject
class User extends Authenticatable implements JWTSubject
{
...
// 实现下面两个方法
public function getJWTIdentifier()
{
return $this->getKey();
}
public function getJWTCustomClaims()
{
return [];
}
}
5. 使用 tinker 测试一下是否安装成功。首先使用 User::create 创建一个用户,接着用 Auth::guard('api')->login($user) 生成 token
sail@0f05d28f0693:/var/www/html$ php artisan tinker
Psy Shell v0.11.8 (PHP 8.1.9 — cli) by Justin Hileman
>>>
>>> User::create([
... 'name' => 'test',
... 'email' => 'test@qq.com',
... 'password' => encrypt('123456')
... ])
[!] Aliasing 'User' to 'App\Models\User' for this Tinker session.
=> App\Models\User {#3681
name: "test",
email: "test@qq.com",
#password: "eyJpdiI6ImUya2MwdnhRelhiaFhzTzMyWlNCNkE9PSIsInZhbHVlIjoiRzNCcytTV2JwbTc2enhNVDNYSlNOQT09IiwibWFjIjoiNDgxM2VjNmNkMzk5MDJmMDEyMDdlM2VmNzlkM2FkMTFiNzAwYzVhMmUzZDRmMTNmY2I4YTg3OWY4YmVmNTI1YiIsInRhZyI6IiJ9",
updated_at: "2022-09-15 00:57:38",
created_at: "2022-09-15 00:57:38",
id: 1,
}
>>>
>>> $user = User::where('name', 'test')->first();
=> App\Models\User {#4479
id: 1,
name: "test",
email: "test@qq.com",
email_verified_at: null,
#password: "eyJpdiI6ImUya2MwdnhRelhiaFhzTzMyWlNCNkE9PSIsInZhbHVlIjoiRzNCcytTV2JwbTc2enhNVDNYSlNOQT09IiwibWFjIjoiNDgxM2VjNmNkMzk5MDJmMDEyMDdlM2VmNzlkM2FkMTFiNzAwYzVhMmUzZDRmMTNmY2I4YTg3OWY4YmVmNTI1YiIsInRhZyI6IiJ9",
#remember_token: null,
created_at: "2022-09-15 00:57:38",
updated_at: "2022-09-15 00:57:38",
}
>>>
>>> Auth::guard('api')->login($user);
=> "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJodHRwOi8vYXBpLnRlc3QiLCJpYXQiOjE2NjMyMDM1MDMsImV4cCI6MTY2MzIwNzEwMywibmJmIjoxNjYzMjAzNTAzLCJqdGkiOiJNNE94Q0Y2cktyRHZrME44Iiwic3ViIjoiMSIsInBydiI6IjIzYmQ1Yzg5NDlmNjAwYWRiMzllNzAxYzQwMDg3MmRiN2E1OTc2ZjcifQ.ccq-2iOinoBCK6nWwtgkxeR9gOItCfEC7-QOim7qRH4"
>
6. token 生成成功,接下去就可以封装登录逻辑了。