[http://www.koukousky.com/back/2483.html](http://www.koukousky.com/back/2483.html)
> github:[https://github.com/lcobucci/jwt/tree/3.4](https://github.com/lcobucci/jwt/tree/3.4)
#### 1.安裝
~~~php
"lcobucci/jwt": "^3.4"版本
php >= 5.6
OpenSSL Extension
// 安裝
$ composer require lcobucci/jwt
~~~
### 2\. 一些參數說明
~~~php
iss 【issuer】簽發人(可以是,發布者的url地址)
sub 【subject】該JWT所面向的用戶,用于處理特定應用,不是常用的字段
aud 【audience】受眾人(可以是客戶端的url地址,用作驗證是否是指定的人或者url)
exp 【expiration】 該jwt銷毀的時間;unix時間戳
nbf 【not before】 該jwt的使用時間不能早于該時間;unix時間戳
iat 【issued at】 該jwt的發布時間;unix 時間戳
jti 【JWT ID】 該jwt的唯一ID編號
~~~
### 3.使用
~~~php
<?php
//生成token
Service::createToken();
//解析token
Service::parseToken($token);
//驗證token
Service::validationToken($token);
?>
~~~
#### 簡單封裝
~~~php
<?php
/**
* jwt封裝的一個簡單的類
*/
use Lcobucci\JWT\Configuration;
use Lcobucci\JWT\Signer\Hmac\Sha256;
use Lcobucci\JWT\Signer\Key\InMemory;
use DateTimeImmutable;
use Lcobucci\JWT\Token\Plain;
use Lcobucci\JWT\Validation\RequiredConstraintsViolated;
use Lcobucci\JWT\Validation\Constraint\SignedWith;
class Service
{
/**
* 配置秘鑰加密
* @return Configuration
*/
public static function getConfig()
{
$configuration = Configuration::forSymmetricSigner(
// You may use any HMAC variations (256, 384, and 512)
new Sha256(),
// replace the value below with a key of your own!
InMemory::base64Encoded('YWFhc0pOU0RLSkJITktKU0RiamhrMTJiM2Joa2ox')
// You may also override the JOSE encoder/decoder if needed by providing extra arguments here
);
return $configuration;
}
/**
* 簽發令牌
*/
public static function createToken()
{
$config = self::getConfig();
assert($config instanceof Configuration);
$now = new DateTimeImmutable();
$token = $config->builder()
// 簽發人
->issuedBy('http://example.com')
// 受眾
->permittedFor('http://example.org')
// JWT ID 編號 唯一標識
->identifiedBy('123')
// 簽發時間
->issuedAt($now)
// 在1分鐘后才可使用
// ->canOnlyBeUsedAfter($now->modify('+1 minute'))
// 過期時間1小時
->expiresAt($now->modify('+1 hour'))
// 自定義uid 額外參數
->withClaim('uid', 1)
// 自定義header 參數
->withHeader('foo', 'bar')
// 生成token
->getToken($config->signer(), $config->signingKey());
//result:
//eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiIsImZvbyI6ImJhciJ9.eyJpc3MiOiJodHRwOlwvXC9leGFtcGxlLmNvbSIsImF1ZCI6Imh0dHA6XC9cL2V4YW1wbGUub3JnIiwianRpIjoiNGYxZzIzYTEyYWEiLCJpYXQiOjE2MDk0Mjk3MjMsIm5iZiI6MTYwOTQyOTc4MywiZXhwIjoxNjA5NDMzMzIzLCJ1aWQiOjF9.o4uLWzZjk-GJgrxgirypHhXKkMMUEeL7z7rmvmW9Mnw
//base64 decode:
//{"typ":"JWT","alg":"HS256","foo":"bar"}{"iss":"http:\/\/example.com","aud":"http:\/\/example.org","jti":"4f1g23a12aa","iat":1609429723,"nbf":1609429783,"exp":1609433323,"uid":1}[6cb`"*Gr0ńx?oL
return $token->toString();
}
/**
* 解析令牌
*/
public static function parseToken(string $token)
{
$config = self::getConfig();
assert($config instanceof Configuration);
$token = $config->parser()->parse('eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiIsImZvbyI6ImJhciJ9.eyJpc3MiOiJodHRwOlwvXC9leGFtcGxlLmNvbSIsImF1ZCI6Imh0dHA6XC9cL2V4YW1wbGUub3JnIiwianRpIjoiNGYxZzIzYTEyYWEiLCJpYXQiOjE2MDk0Mjk3MjMsIm5iZiI6MTYwOTQyOTc4MywiZXhwIjoxNjA5NDMzMzIzLCJ1aWQiOjF9.o4uLWzZjk-GJgrxgirypHhXKkMMUEeL7z7rmvmW9Mnw'
);
assert($token instanceof Plain);
dump($token->headers()); // Retrieves the token headers
dump($token->claims()); // Retrieves the token claims
}
/**
* 驗證令牌
*/
public static function validationToken(string $token)
{
$config = self::getConfig();
assert($config instanceof Configuration);
$token = $config->parser()->parse($token);
assert($token instanceof Plain);
//Lcobucci\JWT\Validation\Constraint\IdentifiedBy: 驗證jwt id是否匹配
//Lcobucci\JWT\Validation\Constraint\IssuedBy: 驗證簽發人參數是否匹配
//Lcobucci\JWT\Validation\Constraint\PermittedFor: 驗證受眾人參數是否匹配
//Lcobucci\JWT\Validation\Constraint\RelatedTo: 驗證自定義cliam參數是否匹配
//Lcobucci\JWT\Validation\Constraint\SignedWith: 驗證令牌是否已使用預期的簽名者和密鑰簽名
//Lcobucci\JWT\Validation\Constraint\ValidAt: 驗證要求iat,nbf和exp(支持余地配置)
//驗證jwt id是否匹配
$validate_jwt_id = new \Lcobucci\JWT\Validation\Constraint\IdentifiedBy('123');
$config->setValidationConstraints($validate_jwt_id);
//驗證簽發人url是否正確
$validate_issued = new \Lcobucci\JWT\Validation\Constraint\IssuedBy('http://example.com');
$config->setValidationConstraints($validate_issued);
//驗證客戶端url是否匹配
$validate_aud = new \Lcobucci\JWT\Validation\Constraint\PermittedFor('http://example.org');
$config->setValidationConstraints($validate_aud);
//驗證是否過期
$timezone = new \DateTimeZone('Asia/Shanghai');
$now = new \Lcobucci\Clock\SystemClock($timezone);
$validate_jwt_at = new \Lcobucci\JWT\Validation\Constraint\ValidAt($now);
$config->setValidationConstraints($validate_jwt_at);
$constraints = $config->validationConstraints();
try {
$config->validator()->assert($token, ...$constraints);
} catch (RequiredConstraintsViolated $e) {
// list of constraints violation exceptions:
var_dump($e->violations());
}
}
}
~~~
* [上一篇](http://www.koukousky.com/back/2481.html)
* [下一篇](http://www.koukousky.com/back/2519.html)
版權屬于:[KouKou](http://www.koukousky.com/)
原文地址:[http://www.koukousky.com/back/2483.html](http://www.koukousky.com/back/2483.html)
轉載時必須以鏈接形式注明原始出處及本聲明。
- 空白目錄1
- RBAC
- RBAC權限模型[完整]
- 你知道權限管理的RBAC模型嗎?
- rbac 一個用戶對應多個賬號_如何設計一個強大的權限系統
- Postman 快速使用(設置環境變量)
- postman的使用方法詳解!最全面的教程
- Postman常用的幾個功能
- ThinkPHP項目總結
- thinkphp5 遞歸查詢所有子代,查詢上級,并且獲取層級
- PHP原生項目之留言板
- 智慧校園
- PHP如何實現訂單的延時處理詳解
- VUE
- const {data:res} = await login(this.loginForm)
- Vue中的async和await的使用
- PHP實現消息推送(定時輪詢)
- tp5 計算兩個日期之間相差的天數
- 使用jquery的ajax方法獲取下拉列表值
- jQuery實現select下拉框選中數據觸發事件
- SetFocus 方法
- 快來了解下TP6中的超級函數app()!
- PHP socket 服務器框架 workerman
- 程序員如何才能成為獨立開發者?
- PHP 錯誤處理
- php面向對象類中的$this,static,final,const,self及雙冒號 :: 這幾個關鍵字使用方法。
- 小白教你玩轉php的閉包
- 關于TP6項目搭建的坑(多應用模式)
- ThinkPHP6.0 與5.0的差別及坑點
- axios在vue項目中的使用實例詳解
- php中的類、對象、方法是指什么
- 聊一聊PHP的依賴注入(DI) 和 控制反轉(IoC)
- 深入理解控制反轉(IoC)和依賴注入(DI)
- Private,Public,Protected
- ThinkPHP5(目錄,路徑,模式設置,命名空間)
- 在 ThinkPHP6 中使用 Workerman
- 介紹thinkphp lock鎖的使用和例子
- php中_initialize()函數與 __construct()函數的區別說明
- api接口數據-驗證-整理
- api接口數據-驗證-整理【續】
- TP6容易踩得坑【原創】
- TP6的日志怎么能記錄詳細的日志?
- 是否需要模型分層
- PHP面試題 全網最硬核面試題來了 2021年學習面試跳槽必備(一)
- MySQL單表數據量過千萬,采坑優化記錄,完美解決方案
- MySql表分區(根據時間timestamp)
- MySQL大表優化方案
- 閑言碎語
- 數據庫外鍵的使用
- 深入理解thinkphp、laravel等框架中容器概念
- vue做前端,thinkphp6做后臺,項目部署
- 簡單MVC架構的PHP留言本
- TP5里面extend和vendor的區別
- 在mysql數據庫中制作千萬級測試表
- MySQL千萬級的大表要怎么優化
- ThinkPHP關聯模型操作實例分析
- lcobucci/jwt —— 一個輕松生成jwt token的插件
- RESTful API 設計指南
- MySQL如何為表字段添加索引
- ThinkPHP6.0快速開發手冊(案例版)
- tp5 靜態方法和普通方法的區別
- 數據字典功能
- mysql中的數據庫ID主鍵的設置問題
- 基于角色的權限控制(django內置auth體系)
- RBAC系統經典五張表
- 什么是接口文檔,如何寫接口,有什么規范?
- thinkphp5.0自定義驗證器