Thinkphp使用jwt创建和读取 | 熊阿哥博客

Thinkphp使用jwt创建和读取

Thinkphp   2025-01-18 13:13   94   0  

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;
    }
 }


博客评论
还没有人评论,赶紧抢个沙发~
发表评论
说明:请文明发言,共建和谐网络,您的个人信息不会被公开显示。