JwtTokenService.php 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. <?php
  2. /**
  3. * @package merchant
  4. *
  5. * @author xaboy
  6. * @day 2020-04-09
  7. *
  8. *
  9. */
  10. namespace crmeb\services;
  11. use crmeb\exceptions\AuthException;
  12. use Firebase\JWT\BeforeValidException;
  13. use Firebase\JWT\ExpiredException;
  14. use Firebase\JWT\JWT;
  15. use Firebase\JWT\SignatureInvalidException;
  16. use think\facade\Config;
  17. use UnexpectedValueException;
  18. class JwtTokenService
  19. {
  20. /**
  21. * @param int $id
  22. * @param string $type
  23. * @param array $params
  24. * @return array
  25. * @author xaboy
  26. * @day 2020-04-09
  27. */
  28. public function createToken(int $id, string $type, array $params = [])
  29. {
  30. $time = time();
  31. $host = app('request')->host();
  32. $exp = intval(Config::get('admin.token_ext', 3000));
  33. $params += [
  34. 'iss' => $host,
  35. 'aud' => $host,
  36. 'iat' => $time,
  37. 'nbf' => $time,
  38. 'exp' => strtotime("+ {$exp}hour"),
  39. ];
  40. $params['jti'] = [$id, $type];
  41. $token = JWT::encode($params, Config::get('app.app_key', 'default'));
  42. $params['token'] = $token;
  43. $params['out'] = 3000 * 60 * 60;
  44. return $params;
  45. }
  46. /**
  47. * @param string $token
  48. * @return object
  49. * @throws SignatureInvalidException Provided JWT was invalid because the signature verification failed
  50. * @throws BeforeValidException Provided JWT is trying to be used before it's eligible as defined by 'nbf'
  51. * @throws BeforeValidException Provided JWT is trying to be used before it's been created as defined by 'iat'
  52. * @throws ExpiredException Provided JWT has since expired, as defined by the 'exp' claim
  53. * @throws UnexpectedValueException Provided JWT was invalid
  54. * @author xaboy
  55. * @day 2020-04-09
  56. */
  57. public function parseToken(string $token)
  58. {
  59. return JWT::decode($token, Config::get('app.app_key', 'default'), array('HS256'));
  60. }
  61. /**
  62. * @param string $token
  63. * @return object
  64. * @author xaboy
  65. * @day 2020-04-10
  66. */
  67. public function decode(string $token)
  68. {
  69. $tks = explode('.', $token);
  70. if (count($tks) != 3)
  71. throw new AuthException('Invalid token');
  72. if (null === $payload = JWT::jsonDecode(JWT::urlsafeB64Decode($tks[1])))
  73. throw new AuthException('Invalid token');
  74. return $payload;
  75. }
  76. }