jwt.php 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. <?php
  2. /**
  3. * User: ssh
  4. * Date: 2019/11/20
  5. * Time: 23:21
  6. */
  7. namespace common\components;
  8. use bizHd\wx\services\WxOpenService;
  9. use Lcobucci\JWT\Builder;
  10. use Lcobucci\JWT\Parser;
  11. use Lcobucci\JWT\ValidationData;
  12. use Lcobucci\JWT\Signer\Key;
  13. use Lcobucci\JWT\Signer\Hmac\Sha256;
  14. use Yii;
  15. class jwt
  16. {
  17. //返回一个新的token ssh 2019.11.22
  18. public static function getNewToken($uniqueId)
  19. {
  20. $time = time();
  21. $signer = new Sha256();
  22. $salt = Yii::$app->params['secretKey'];
  23. $key = new Key($salt);
  24. $host = httpUtil::getHost();
  25. $sourceId = httpUtil::getSourceId();
  26. $jwtId = $sourceId . '_' . $uniqueId;
  27. $token = (new Builder())->issuedBy($host)//发布者的url地址
  28. ->canOnlyBeUsedBy($host)//接受者的url地址
  29. ->identifiedBy($jwtId, true)//该jwt的唯一ID编号
  30. ->issuedAt($time)//该jwt的发布时间
  31. ->canOnlyBeUsedAfter($time)//该jwt的使用时间不能早于该时间
  32. ->expiresAt($time + 94608000)//该jwt销毁的时间(3年)
  33. ->set('uniqueId', $uniqueId)
  34. ->set('sourceId', $sourceId)
  35. ->sign($signer, $key)->getToken();
  36. return (string)$token;
  37. }
  38. public static function getKeyName($sourceId, $uniqueId)
  39. {
  40. return 'JWT_' . $sourceId . '_' . $uniqueId;
  41. }
  42. //验证token
  43. public static function validate($token)
  44. {
  45. $token = (new Parser())->parse($token);
  46. //数据校验
  47. $data = new ValidationData();//使用当前时间来校验数据
  48. // if (!$token->validate($data)) {
  49. // Yii::info('token时间验证没有通过。token:' . $token);
  50. // return 0;
  51. // }
  52. //token校验
  53. $signer = new Sha256();//生成JWT时使用的加密方式
  54. $salt = Yii::$app->params['secretKey'];
  55. if (!$token->verify($signer, new Key($salt))) {
  56. Yii::info('token解密没有通过。token:' . $token);
  57. return 0;
  58. }
  59. $token->getHeaders(); // 获取JWT的Header(头部)信息
  60. $token->getClaims(); // 获取JWT的PayLoad(负载)信息
  61. $uniqueId = $token->getClaim('uniqueId');
  62. $sourceId = $token->getClaim('sourceId');
  63. $currentSourceId = httpUtil::getSourceId();
  64. if ($sourceId != $currentSourceId) {
  65. return 0;
  66. }
  67. // if (!$token->validate($data)) {
  68. // Yii::info('token时间验证没有通过,但还是返回了uniqueId:'.$uniqueId.'。 token:' . $token);
  69. // }
  70. return $uniqueId;
  71. }
  72. //判断有没登陆并返回id ssh 2019.11.22
  73. public static function getLoginId()
  74. {
  75. $token = httpUtil::getToken();
  76. if (empty($token)) {
  77. return 0;
  78. }
  79. return self::validate($token);
  80. }
  81. }