JwtTokenService.php 2.2 KB

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