项目根目录composer下载
引入php-jwt包
composer require firebase/php-jwt
封装方法
$user_id,
//签发组织
"iss" => env("TOKEN.iss",""),
//签发作者
"aud" => env("TOKEN.aud",""),
//签发时间
"iat" => $time,
//生效时间
"nbf" => $time,
//过期时间
"exp" => $expire
);
//返回token结果
return json(JWTUtil::encode($token,$key));
}
public static function verifyJwt($jwt)
{
//jwt的签发密钥,验证token的时候需要用到
$key = md5(env("TOKEN.iss"));
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($authInfo);
}catch (ExpiredException $e){
return json(['code'=>501,'data'=>[],'msg'=>'token已经过期']);
}catch (Exception $e){
return json(['code'=>$e->getCode(),'msg'=>$e->getMessage(),'data'=>[]]);
}
}
public static function getRequestToken()
{
if (empty($_SERVER['HTTP_AUTHORIZATION'])) {
return false;
}
$header = $_SERVER['HTTP_AUTHORIZATION'];
$method = 'bearer';
//去除token中可能存在的bearer标识
return trim(str_ireplace($method, '', $header));
}
}
控制器调用封装方法即可



