Thinkphp控制器文件:
<?php
declare(strict_types=1); //代码严格模式
namespace app\index\controller;
use think\Request;
use think\facade\Db;
use Firebase\JWT\JWT;
use Firebase\JWT\Key;
use Firebase\JWT\SignatureInvalidException;
date_default_timezone_set("PRC");
class Byd extends \app\BaseController{
//创建jwt
public function createjwt(){
$h = 168; // 有效期7天
$key = $this->jwtkey;
$time = time(); //签发时间
$expire = $time + $h * 3600; //过期时间 14400 4小时
$iss = "trailer_zhengyun_system";
$tokenparam = array(
"data" => [],
"iss" => $iss, //jwt签发者
"aud" => "ZY", //签发作者
"iat" => $time, //签发时间
"nbf" => $time, //生效时间,定义在什么时间之前
"exp" => $expire //过期时间,这个过期时间必须要大于签发时间
);
$token = JWT::encode($tokenparam,$key,'HS256');
$absolutePath = realpath('jwtoken.txt');
// $absolutePath = dirname(__FILE__) . '/' . $path;
$writedata = [
'exptime'=>$expire,
'token'=>$token
];
file_put_contents($absolutePath,json_encode($writedata));
// return JWT::encode($token, $key,'HS256');
}
//验证jwt并返回TOKEN
public function returnjwtoken(){
$getjwtoken = file_get_contents(realpath('jwtoken.txt'));
$getjwtokenarr = json_decode($getjwtoken,true);
$getjwtokenarrexptime = $getjwtokenarr['exptime'];
$getnewjwtokenvalue = $getjwtokenarr['token'];
$getnewjwtoken = '';
$getnewjwtokenarr = '';
//判断TOKEN的时间是否超过当前时间,即是否过期
if($getjwtokenarrexptime<=time()){
$this->createjwt(); // 从请求中获取JWT
$getnewjwtoken = file_get_contents(realpath('jwtoken.txt'));
$getnewjwtokenarr = json_decode($getnewjwtoken,true);
$getnewjwtokenvalue = $getnewjwtokenarr['token'];
}
return $getnewjwtokenvalue;
}
}