| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109 |
- <?php
- namespace api\components;
- /**
- * Created by PhpStorm.
- * User: shizhongqi
- * Date: 2019/11/19
- * Time: 21:37
- */
- use Lcobucci\JWT\Builder;
- use Lcobucci\JWT\Claim\Factory as ClaimFactory;
- use Lcobucci\JWT\Parser;
- use Lcobucci\JWT\Parsing\Decoder;
- use Lcobucci\JWT\Parsing\Encoder;
- use Lcobucci\JWT\Signer\Key;
- use Lcobucci\JWT\Token;
- use Lcobucci\JWT\ValidationData;
- use Yii;
- //use yii\base\Component;
- use yii\base\InvalidParamException;
- class Jwt
- {
- /**
- * @var array 支持的加密算法
- */
- public $supportedAlgs = [
- 'HS256' => 'Lcobucci\JWT\Signer\Hmac\Sha256',
- 'HS384' => 'Lcobucci\JWT\Signer\Hmac\Sha384',
- 'HS512' => 'Lcobucci\JWT\Signer\Hmac\Sha512',
- ];
- /**
- * 创建JWT生成器
- * @param Encoder|null $encoder
- * @param ClaimFactory|null $claimFactory
- * @return Builder
- */
- public function getBuilder(Encoder $encoder = null, ClaimFactory $claimFactory = null)
- {
- return new Builder($encoder, $claimFactory);
- }
- /**
- * 创建JWT解析器
- * @param Decoder|null $decoder
- * @param ClaimFactory|null $claimFactory
- * @return Parser
- */
- public function getParser(Decoder $decoder = null, ClaimFactory $claimFactory = null)
- {
- return new Parser($decoder, $claimFactory);
- }
- /**
- * 验证JWT,并返回一个令牌类
- * @param $token
- * @param bool $validate
- * @param bool $verify
- * @return Token|null
- */
- public function validateJwt($token, $validate = true, $verify = true)
- {
- try {
- $token = $this->getParser()->parse((string)$token);
- } catch (\RuntimeException $e) {
- // Yii::warning("Invalid JWT provided: " . $e->getMessage(), 'jwt');
- return null;
- } catch (\InvalidArgumentException $e) {
- // Yii::warning("Invalid JWT provided: " . $e->getMessage(), 'jwt');
- return null;
- }
- if ($validate && !$this->validateToken($token)) {
- return null;
- }
- if ($verify && !$this->verifyToken($token)) {
- return null;
- }
- return $token;
- }
- /**
- * 数据验证
- * @param Token $token
- * @param null $currentTime
- * @return bool
- */
- public function validateToken(Token $token, $currentTime = null)
- {
- $data = new ValidationData($currentTime);
- // @todo Add claims for validation
- return $token->validate($data);
- }
- /**
- * Validate token
- * @param Token $token
- * @return bool
- */
- public function verifyToken(Token $token)
- {
- $alg = $token->getHeader('alg');
- if (empty($this->supportedAlgs[$alg])) {
- throw new InvalidParamException('Algorithm not supported');
- }
- $signer = Yii::createObject($this->supportedAlgs[$alg]);
- return $token->verify($signer, new Key('jwt_secret'));
- }
- }
|