12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879 |
- <?php
- namespace app\common\model\base\user;
- /**
- * @title : JWT的token验证
- * @desc : 安装依赖包composer require firebase/php-jwt
- * @Author : wangkewei
- * @Date : 2023-05-24 15:10:25
- */
- use Firebase\JWT\Key;
- use Firebase\JWT\JWT;
- use think\facade\Config;
- class JwtToken
- {
- /**
- * @title: 获取加密解密使用的盐值
- * @desc: 描述
- * @return {*}
- * @author: wangkewei
- * @method: POST
- * @Date: 2023-05-24 15:15:40
- */
- static public function getSalt():string
- {
- if(empty($salt=Config::get('develop.jwt_salt'))){
- throw new \Exception("jwt缺少加密用的盐值");
- }
- return $salt;
- }
- /**
- * @title: jwt生成token
- * @desc: 描述
- * @param {array} {userinfo} {} {用户信息}
- * @param {string} {aud} {} {签名对象}
- * @return {*}
- * @author: wangkewei
- * @method: POST
- * @Date: 2023-05-24 15:16:10
- */
- static public function Encode(array $userinfo,string $aud='')
- {
- $salt = self::getSalt();
- $token = [
- 'iss'=>'0.0.0.0',
- 'aud'=>$aud,
- 'iat'=>time(),
- 'nbf'=>time(),
- 'exp'=>time()+604800,
- 'data'=>$userinfo,
- ];
- return JWT::encode($token,$salt,'HS256');
- }
- /**
- * @title: jwt解码token
- * @desc: 描述
- * @param {string} {aud} {} {签名对象}
- * @return {*}
- * @author: wangkewei
- * @method: POST
- * @Date: 2023-05-24 15:16:45
- */
- static public function Decode(string $token,string $aud='')
- {
- $salt = self::getSalt();
- try {
- JWT::$leeway = 60;
- $decoded = JWT::decode($token, new Key($salt, 'HS256'),array('HS256'));
- $decoded = json_decode(json_encode($decoded,JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT),true);
- if($aud != $decoded['aud'])
- throw new \Exception('用户信息无效,请重新登录');
- return Result(1,'解码成功',$decoded['data']);
- } catch (\Firebase\JWT\SignatureInvalidException $e) {
- throw new \Exception('用户信息无效,请重新登录');
- } catch (\Firebase\JWT\BeforeValidException|\Firebase\JWT\ExpiredException $e) {
- throw new \Exception('验证已过期,请重新登录');
- } catch (\Exception $e) {
- throw new \Exception('未知错误:'.$e->getMessage());
- }
- }
- }
|