JwtAuthModelTrait.php 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. <?php
  2. // +----------------------------------------------------------------------
  3. // | CRMEB [ CRMEB赋能开发者,助力企业发展 ]
  4. // +----------------------------------------------------------------------
  5. // | Copyright (c) 2016~2020 https://www.crmeb.com All rights reserved.
  6. // +----------------------------------------------------------------------
  7. // | Licensed CRMEB并不是自由软件,未经许可不能去掉CRMEB相关版权
  8. // +----------------------------------------------------------------------
  9. // | Author: CRMEB Team <admin@crmeb.com>
  10. // +----------------------------------------------------------------------
  11. namespace qiniu\traits;
  12. use Firebase\JWT\BeforeValidException;
  13. use Firebase\JWT\ExpiredException;
  14. use Firebase\JWT\JWT;
  15. use Firebase\JWT\Key;
  16. use Firebase\JWT\SignatureInvalidException;
  17. use think\facade\Env;
  18. use UnexpectedValueException;
  19. trait JwtAuthModelTrait
  20. {
  21. /**
  22. * @param string $type
  23. * @param array $params
  24. * @return array
  25. */
  26. public function getToken(string $type, array $params = []): array
  27. {
  28. $id = $this->{$this->getPk()};
  29. $host = app()->request->host();
  30. $time = time();
  31. $params += [
  32. 'iss' => $host,
  33. 'aud' => $host,
  34. 'iat' => $time,
  35. 'nbf' => $time,
  36. 'exp' => strtotime('+ 3hour'),
  37. ];
  38. $params['jti'] = compact('id', 'type');
  39. $token = JWT::encode($params, Env::get('app.app_key', 'default'), 'HS256');
  40. return compact('token', 'params');
  41. }
  42. /**
  43. * @param string $jwt
  44. * @return array
  45. *
  46. * @throws UnexpectedValueException Provided JWT was invalid
  47. * @throws SignatureInvalidException Provided JWT was invalid because the signature verification failed
  48. * @throws BeforeValidException Provided JWT is trying to be used before it's eligible as defined by 'nbf'
  49. * @throws BeforeValidException Provided JWT is trying to be used before it's been created as defined by 'iat'
  50. * @throws ExpiredException Provided JWT has since expired, as defined by the 'exp' claim
  51. *
  52. */
  53. public static function parseToken(string $jwt): array
  54. {
  55. JWT::$leeway = 60;
  56. $key = new Key(Env::get('app.app_key', 'default'), 'HS256');
  57. $data = JWT::decode($jwt, $key);
  58. $model = new self();
  59. return [$model->where($model->getPk(), $data->jti->id)->find(), $data->jti->type];
  60. }
  61. }