ThinkChat🤖让你学习和工作更高效,注册即送10W Token,即刻开启你的AI之旅 广告
# 验证令牌 *此处的示例从假设的依赖注入容器中获取配置对象。您可以在同一个脚本中创建它或从不同的文件中要求它。它基本上取决于您的系统是如何引导的。* 要验证令牌,您必须创建一个新的验证器(使用[配置对象时更容易)并断言或验证令牌。 ## 使用`Lcobucci\JWT\Validator#assert()` **警告** 你**必须**至少提供一个约束,否则`\Lcobucci\JWT\Validation\NoConstraintsGiven`会抛出异常。 此方法遍历集合中的每个约束,将所有违规分组,并使用分组违规引发异常: ~~~php use Lcobucci\JWT\Configuration; use Lcobucci\JWT\UnencryptedToken; use Lcobucci\JWT\Validation\RequiredConstraintsViolated; $config = $container->get(Configuration::class); assert($config instanceof Configuration); $token = $config->parser()->parse('...'); assert($token instanceof UnencryptedToken); $constraints = $config->validationConstraints(); try { $config->validator()->assert($token, ...$constraints); } catch (RequiredConstraintsViolated $e) { var_dump($e->violations()); } ~~~ ## 使用`Lcobucci\JWT\Validator#validate()` **警告** 你**必须**至少提供一个约束,否则`\Lcobucci\JWT\Validation\NoConstraintsGiven`会抛出异常。 这里的区别在于我们总是会得到`boolean`结果并在第一次违规时停止: ~~~php use Lcobucci\JWT\Configuration; use Lcobucci\JWT\UnencryptedToken; $config = $container->get(Configuration::class); assert($config instanceof Configuration); $token = $config->parser()->parse('...'); assert($token instanceof UnencryptedToken); $constraints = $config->validationConstraints(); if (! $config->validator()->validate($token, ...$constraints)) { throw new RuntimeException('No way!'); } ~~~ ## 可用约束 该库提供以下约束: * `Lcobucci\JWT\Validation\Constraint\IdentifiedBy`: 验证声明是否`jti`与预期值匹配 * `Lcobucci\JWT\Validation\Constraint\IssuedBy`: 验证声明`iss`是否被列为预期值 * `Lcobucci\JWT\Validation\Constraint\PermittedFor`: 验证声明是否`aud`包含预期值 * `Lcobucci\JWT\Validation\Constraint\RelatedTo`: 验证声明是否`sub`与预期值匹配 * `Lcobucci\JWT\Validation\Constraint\SignedWith`: 验证令牌是否使用预期的签名者和密钥签名 * `Lcobucci\JWT\Validation\Constraint\StrictValidAt`: 验证声明的存在和有效性`iat`,`nbf`, and`exp`(支持 leeway 配置) * `Lcobucci\JWT\Validation\Constraint\LooseValidAt`: 验证声明`iat`,`nbf`, and`exp`, 当存在时(支持 leeway 配置) 您还可以创建自己的验证约束