项目根目录composer下载
引入php-jwt包
composer require firebase/php-jwt
封装方法
<?php
namespace app\business;
use Firebase\JWT\ExpiredException;
use Firebase\JWT\JWT as JWTUtil;
class JWT
{
/**
* 根据json web token设置的规则生成token
* @param $user_id
* @return \think\response\Json
*/
public static function createJwt($user_id)
{
//jwt的签发密钥,验证token的时候需要用到
$key = md5(env("TOKEN.key",""));
//签发时间
$time = time();
//过期时间
$expire = $time + 14400;
$token = array(
//用户
"user_id" => $user_id,
//签发组织
"iss" => env("TOKEN.iss",""),
//签发作者
"aud" => env("TOKEN.aud",""),
//签发时间
"iat" => $time,
//生效时间
"nbf" => $time,
//过期时间
"exp" => $expire
);
//返回token结果
return json(JWTUtil::encode($token,$key));
}
/**
* 进行token认证
* @param $jwt
* @return \think\response\Json
*/
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'=>[]]);
}
}
/**从请求信息中获取token令牌
* @return false|string
*/
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));
}
}
控制器调用封装方法即可
|