首先安装JTW扩展
composer require firebase/php-jwt
首先封装一个类叫JWT
在里面添加如下代码
两个方法,一个为生成token 一个为检测token
<?php
namespace app\admin\business;
use Firebase\JWT\ExpiredException;
use Firebase\JWT\JWT as JWTUtil;
use think\Exception;
use think\response\Json;
class JWT
{
/**
* 根据json web token设置的规则生成token
* @return \think\response\Json
*/
public static function createjwt($userid)
{
$key = md5(env('TOKEN.key')); //jwt的签发密钥,验证token的时候需要用到
$time = time(); //签发时间
$expire = $time + 14400; //过期时间
$token = array(
"user_id" => $userid,
"iss" => env('TOKEN.iss'),//签发组织
"aud" => env('TOKEN.aud'), //签发作者
"iat" => $time,
"nbf" => $time,
"exp" => $expire
);
return JWTUtil::encode($token,$key);
}
/**
* 验证token
* @return \think\response\Json
*/
public static function verifyjwt($jwt)
{
if(in_array($jwt,cache('delete_token'))){
throw new Exception('token过期',"400");
}
$key = md5(env('TOKEN.key')); //jwt的签发密钥,验证token的时候需要用到
try{
$jwtAuth = json_encode(JWTUtil::decode($jwt,$key,array("HS256")));
$authInfo = json_decode($jwtAuth,true);
if (!$authInfo['user_id']){
return \json(['code'=>400,'msg'=>"用户不存在",'data'=>[]]);
}
return \json(['code'=>200,'msg'=>"ok",'data'=>[]]);
}catch (ExpiredException $e){
return \json(['code'=>501,'msg'=>"token过期",'data'=>[]]);
}catch (\Exception $e){
return \json(['code'=>$e->getCode(),'msg'=>$e->getMessage(),'data'=>[]]);
}
}