# 驗證令牌
*此處的示例從假設的依賴注入容器中獲取配置對象。您可以在同一個腳本中創建它或從不同的文件中要求它。它基本上取決于您的系統是如何引導的。*
要驗證令牌,您必須創建一個新的驗證器(使用[配置對象時更容易)并斷言或驗證令牌。
## 使用`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 配置)
您還可以創建自己的驗證約束
- 序言
- ThinkPHP官方資源
- 術語
- 根目錄
- php術語
- jwt
- 下載jwt
- 認識jwt
- 生成token
- 驗證token
- lcobucci/jwt
- 安裝
- 配置
- 生成token
- 解析令牌
- 驗證令牌
- 擴展庫jwt
- thinkPHP使用lcobucci/jwt
- phpmailer
- PHPMailer的使用
- phpMailer config
- 短信驗證嗎
- 阿里云短信驗證碼發送類
- 權限管理
- 基于thinkphp6.0
- 通用函數
- 密碼加密
- 數組
- 數據庫
- 查詢數據
- 添加數據
- 刪除數據
- 批量刪除
- 更新數據
- 請求流程
- thinkphp6安裝
- thinkphp6目錄介紹
- 單應用
- 多應用
- 配置文件
- 模型,模板與Model的區別
- .env介紹
- 入口文件
- 控制器
- model層
- 視圖層
- common公共函數
- 路由
- 命令行
- 常用thinkphp函數和方法
- 高德地圖i定位城市
- 更新日志