builder() // Configures the issuer (iss claim) ->issuedBy(self::$iss) // Configures the audience (aud claim) ->permittedFor(self::$aud) // Configures the id (jti claim) // ->identifiedBy($this->jti) // Configures the time that the token was issue (iat claim) ->issuedAt($now) // Configures the expiration time of the token (exp claim) ->expiresAt($now->modify(sprintf('+%d seconds', $expire))) // Configures a new claim, called "uid" ->withClaim('data', $data) // Configures a new header, called "foo" // ->withHeader('foo', 'bar') // Builds a new token ->getToken(self::config()->signer(), self::config()->signingKey()); return $token->toString(); } /** * 解析 * * @param string $tokenStr * @return array|mixed */ public static function parse(string $tokenStr) { $config = self::config(); try { $token = $config->parser()->parse($tokenStr); assert($token instanceof UnencryptedToken); return $token->claims()->all()['data'] ?? []; } catch (Exception $e) { return []; } } /** * 验证token * * @param string $tokenStr * @return bool */ public static function validate(string $tokenStr): bool { $config = self::config(); try { $token = $config->parser()->parse($tokenStr); assert($token instanceof UnencryptedToken); //验证签发人iss是否正确 $validateIssued = new IssuedBy(self::$iss); $config->setValidationConstraints($validateIssued); //验证客户端aud是否匹配 $validateAud = new PermittedFor(self::$aud); $config->setValidationConstraints($validateAud); //验证是否过期 exp $timezone = new DateTimeZone('Asia/Shanghai'); $now = new SystemClock($timezone); $validateExpired = new LooseValidAt($now); $config->setValidationConstraints($validateExpired); $constraints = $config->validationConstraints(); return $config->validator()->validate($token, ...$constraints); } catch (Exception $e) { return false; } } }