| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889 |
- <?php
- /**
- * User: shish
- * Date: 2019/11/20
- * Time: 23:21
- */
- namespace common\components;
- 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
- public static function create($sourceId, $userId)
- {
- $time = time();
- $signer = new Sha256();
- $salt = Yii::$app->params['secretKey'];
- $key = new Key($salt);
- $host = httpUtil::getHost();
- $uniqueId = $sourceId . '_' . $userId;
- $token = (new Builder())->issuedBy($host)//发布者的url地址
- ->canOnlyBeUsedBy($host)//接受者的url地址
- ->identifiedBy($uniqueId, true)//该jwt的唯一ID编号
- ->issuedAt($time)//该jwt的发布时间
- ->canOnlyBeUsedAfter($time)//该jwt的使用时间不能早于该时间
- ->expiresAt($time + 3600)//该jwt销毁的时间
- ->set('userId', $userId)//设置一个变量
- ->sign($signer, $key)->getToken();
-
- $keyName = self::getKeyName($sourceId, $userId);
- Yii::$app->redis->executeCommand('SET', [$keyName, $token]);
-
- return $token;
- }
-
- public static function getKeyName($sourceId, $userId)
- {
- return 'JWT_' . $sourceId . '_' . $userId;
- }
-
- //返回一个可用的token shish 2019.11.22
- public static function get($sourceId, $userId)
- {
- $keyName = self::getKeyName($sourceId, $userId);
- $cacheToken = Yii::$app->redis->executeCommand('GET', [$keyName]);
- $token = '';
- //从缓存中获取
- if (!empty($cacheToken)) {
- $tokenResource = (new Parser())->parse((string)$cacheToken);
- $data = new ValidationData();
- $r = $tokenResource->validate($data);
- $token = $r == false ? '' : $cacheToken;
- }
- if (empty($token)) {
- $token = self::create($sourceId, $userId);
- }
- return $token;
- }
-
- //验证token
- public static function validate($token)
- {
- $token = (new Parser())->parse($token);
- //数据校验
- $data = new ValidationData(); // 使用当前时间来校验数据
- if (!$token->validate($data)) {
- return ['code' => 1];
- }
- //token校验
- $signer = new Sha256();//生成JWT时使用的加密方式
- $salt = Yii::$app->params['secretKey'];
- if (!$token->verify($signer, new Key($salt))) {
- return ['code' => 1];
- }
- $token->getHeaders(); // 获取JWT的Header(头部)信息
- $token->getClaims(); // 获取JWT的PayLoad(负载)信息
- $userId = $token->getClaim('userId');
- return ['code' => 0, 'data' => ['userId' => $userId]];
- }
-
- }
|