JwtToken.php 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. <?php
  2. namespace app\common\model\base\user;
  3. /**
  4. * @title : JWT的token验证
  5. * @desc : 安装依赖包composer require firebase/php-jwt
  6. * @Author : wangkewei
  7. * @Date : 2023-05-24 15:10:25
  8. */
  9. use Firebase\JWT\Key;
  10. use Firebase\JWT\JWT;
  11. use think\facade\Config;
  12. class JwtToken
  13. {
  14. /**
  15. * @title: 获取加密解密使用的盐值
  16. * @desc: 描述
  17. * @return {*}
  18. * @author: wangkewei
  19. * @method: POST
  20. * @Date: 2023-05-24 15:15:40
  21. */
  22. static public function getSalt():string
  23. {
  24. if(empty($salt=Config::get('develop.jwt_salt'))){
  25. throw new \Exception("jwt缺少加密用的盐值");
  26. }
  27. return $salt;
  28. }
  29. /**
  30. * @title: jwt生成token
  31. * @desc: 描述
  32. * @param {array} {userinfo} {} {用户信息}
  33. * @param {string} {aud} {} {签名对象}
  34. * @return {*}
  35. * @author: wangkewei
  36. * @method: POST
  37. * @Date: 2023-05-24 15:16:10
  38. */
  39. static public function Encode(array $userinfo,string $aud='')
  40. {
  41. $salt = self::getSalt();
  42. $token = [
  43. 'iss'=>'0.0.0.0',
  44. 'aud'=>$aud,
  45. 'iat'=>time(),
  46. 'nbf'=>time(),
  47. 'exp'=>time()+604800,
  48. 'data'=>$userinfo,
  49. ];
  50. return JWT::encode($token,$salt,'HS256');
  51. }
  52. /**
  53. * @title: jwt解码token
  54. * @desc: 描述
  55. * @param {string} {aud} {} {签名对象}
  56. * @return {*}
  57. * @author: wangkewei
  58. * @method: POST
  59. * @Date: 2023-05-24 15:16:45
  60. */
  61. static public function Decode(string $token,string $aud='')
  62. {
  63. $salt = self::getSalt();
  64. try {
  65. JWT::$leeway = 60;
  66. $decoded = JWT::decode($token, new Key($salt, 'HS256'),array('HS256'));
  67. $decoded = json_decode(json_encode($decoded,JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT),true);
  68. if($aud != $decoded['aud'])
  69. throw new \Exception('用户信息无效,请重新登录');
  70. return Result(1,'解码成功',$decoded['data']);
  71. } catch (\Firebase\JWT\SignatureInvalidException $e) {
  72. throw new \Exception('用户信息无效,请重新登录');
  73. } catch (\Firebase\JWT\BeforeValidException|\Firebase\JWT\ExpiredException $e) {
  74. throw new \Exception('验证已过期,请重新登录');
  75. } catch (\Exception $e) {
  76. throw new \Exception('未知错误:'.$e->getMessage());
  77. }
  78. }
  79. }