composer require thans/tp-jwt-auth
//此举将生成jwt.php和.env配置文件
php think jwt:create
jwt.php
return [
'secret' => env('JWT_SECRET'),
//Asymmetric key
'public_key' => env('JWT_PUBLIC_KEY'),
'private_key' => env('JWT_PRIVATE_KEY'),
'password' => env('JWT_PASSWORD'),
//JWT time to live
'ttl' => env('JWT_TTL', 15),//token过期时间,方便测试先调整到15秒过期
//Refresh time to live
'refresh_ttl' => env('JWT_REFRESH_TTL', 1), //单位分钟,指定token过期后,多长一段时间内,使用过期的token能够刷新,最好自动刷新,刷新后会在header里面返回,注意保存
//JWT hashing algorithm
'algo' => env('JWT_ALGO', 'HS256'),
'token_mode' =>['header', 'cookie', 'param'],
'blacklist_storage' => thans\jwt\provider\storage\Tp5::class,
];
.env
APP_DEBUG = true
[JWT]
SECRET=ecaff98fa0d92f8abdcc8e1eee590bb4
TTL=20
// 中间件配置
return [
// 别名或分组
'alias' => [
'jwtAuth' => \thans\jwt\middleware\JWTAuth::class,
/**
* JWTAuthAndRefresh包含jwt验证和token自动刷新的功能,所以一般只需要引入该中间件即可
* jwt自动刷新后会返回新的token,所以需要前端判断是否接收到header的Authorization,有值则保存新的token
*/
'autoRefreshJwt' => \thans\jwt\middleware\JWTAuthAndRefresh::class
],
];
use app\BaseController;
use thans\jwt\facade\JWTAuth;
class Hello extends BaseController
{
protected $middleware = ['autoRefreshJwt'];
public function testJwt():void{
$tokenStr = JWTAuth::getToken();
echo $tokenStr;
}
}
完成!