1.引入php-jwt包
composer require firebase/php-jwt
2.代码
lib类文件:app\api\lib\Jwt.php
<?php namespace app\api\lib; use Firebase\JWT\ExpiredException; use Firebase\JWT\JWT as JWTUtil; use think\Exception; class JWT { /** * 根据json web token设置的规则生成token * @return \think\response\Json */ public static function jwt($user_id=null) { //jwt的签发密钥,验证token的时候需要用到 $key = md5(env('TOKEN.key','pyg')); //签发时间 $time = time(); //过期时间 $expire = $time + 14400; //jwt包含的数据 $token = array( //用户id "user_id" => $user_id, //签发组织 "iss" => env('TOKEN.iss',''), //签发作者 "aud" => env('TOKEN.aud',''), //签发时间 "iat" => $time, //生效时间 "nbf" => $time, //过期时间 "exp" => $expire ); $jwt = JWTUtil::encode($token,$key); return success($jwt); } /** * 验证token * @return \think\response\Json */ public static function verify($jwt) { //查看token是否过期 if(in_array($jwt,cache("delete_token"))){ throw new Exception('token过期',400); } //jwt的签发密钥,验证token的时候需要用到 $key = md5(env('TOKEN.key','pyg')); try{ $jwtAuth = json_encode(JWTUtil::decode($jwt,$key,array("HS256"))); $authInfo = json_decode($jwtAuth,true); if (!$authInfo['user_id']){ return fail('用户不存在'); } //验签成功 return success($authInfo); }catch (ExpiredException $e){ return fail('token过期'); }catch (\Exception $e){ //token被篡改 return fail($e->getMessage(),$e->getCode()); } } /** * 从请求信息中获取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)); } }
因Jwt.php文件中读取了.env配置中的信息
在.env中加入以下内容:
[TOKEN] key = pyg iss=http://www.hahaha.com/ aud=zz
控制器登录方法里调Jwt.php,生成token:
$token = JWT::jwt($arr['id'])->getData(); $token = $token['data'];
控制器退出登录的方法里调Jwt.php,进行token值销毁:
/** * 退出登录 * @return \think\response\Json */ function logout(){ //dd(cache("delete_token")); $token=\app\api\lib\JWT::getRequestToken(); //查看缓存中是否存在delete_token $delete_token=cache('delete_token')?:[]; //将这个token放到delete_token数组中 $delete_token[]=$token; //将数组塞回缓存 cache('delete_token',$delete_token,86400); }