| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091 |
- <?php
- /**
- * User: ssh
- * Date: 2019/11/20
- * Time: 23:21
- */
- namespace common\components;
- use bizHd\wx\services\WxOpenService;
- use Lcobucci\JWT\Builder;
- use Lcobucci\JWT\Parser;
- use Lcobucci\JWT\ValidationData;
- use Lcobucci\JWT\Signer\Key;
- use Lcobucci\JWT\Signer\Hmac\Sha256;
- use Yii;
- class jwt
- {
-
- //返回一个新的token ssh 2019.11.22
- public static function getNewToken($uniqueId)
- {
- $time = time();
- $signer = new Sha256();
- $salt = Yii::$app->params['secretKey'];
- $key = new Key($salt);
- $host = httpUtil::getHost();
- $sourceId = httpUtil::getSourceId();
- $jwtId = $sourceId . '_' . $uniqueId;
- $token = (new Builder())->issuedBy($host)//发布者的url地址
- ->canOnlyBeUsedBy($host)//接受者的url地址
- ->identifiedBy($jwtId, true)//该jwt的唯一ID编号
- ->issuedAt($time)//该jwt的发布时间
- ->canOnlyBeUsedAfter($time)//该jwt的使用时间不能早于该时间
- ->expiresAt($time + 94608000)//该jwt销毁的时间(3年)
- ->set('uniqueId', $uniqueId)
- ->set('sourceId', $sourceId)
- ->sign($signer, $key)->getToken();
-
- return (string)$token;
- }
-
- public static function getKeyName($sourceId, $uniqueId)
- {
- return 'JWT_' . $sourceId . '_' . $uniqueId;
- }
-
- //验证token
- public static function validate($token)
- {
- $token = (new Parser())->parse($token);
- //数据校验
- $data = new ValidationData();//使用当前时间来校验数据
-
- // if (!$token->validate($data)) {
- // Yii::info('token时间验证没有通过。token:' . $token);
- // return 0;
- // }
- //token校验
- $signer = new Sha256();//生成JWT时使用的加密方式
- $salt = Yii::$app->params['secretKey'];
- if (!$token->verify($signer, new Key($salt))) {
- Yii::info('token解密没有通过。token:' . $token);
- return 0;
- }
- $token->getHeaders(); // 获取JWT的Header(头部)信息
- $token->getClaims(); // 获取JWT的PayLoad(负载)信息
- $uniqueId = $token->getClaim('uniqueId');
- $sourceId = $token->getClaim('sourceId');
- $currentSourceId = httpUtil::getSourceId();
- if ($sourceId != $currentSourceId) {
- return 0;
- }
- // if (!$token->validate($data)) {
- // Yii::info('token时间验证没有通过,但还是返回了uniqueId:'.$uniqueId.'。 token:' . $token);
- // }
- return $uniqueId;
- }
-
- //判断有没登陆并返回id ssh 2019.11.22
- public static function getLoginId()
- {
- $token = httpUtil::getToken();
- if (empty($token)) {
- return 0;
- }
- return self::validate($token);
- }
- }
|