官網(wǎng) https://jwt.io/
3.0版本 https://github.com/lcobucci/jwt
安裝
composer require lcobucci/jwt
依賴
- PHP 5.5+ (v3.2) and PHP 7.1 (v4.x)
- OpenSSL Extension
示例
獲取token
<?php
use \Lcobucci\JWT\Builder;
use \Lcobucci\JWT\Signer\Hmac\Sha256;
include "../vendor/autoload.php";
$builder = new Builder();
$signer = new Sha256();
$secret = "suspn@)!*";
//設(shè)置header和payload粤铭,以下的字段都可以自定義
$builder->setIssuer("suspn.com") //發(fā)布者
->setAudience("suspn.com") //接收者
->setId("abc", true) //對當(dāng)前token設(shè)置的標(biāo)識
->setIssuedAt(time()) //token創(chuàng)建時間
->setExpiration(time() + 60) //過期時間
->setNotBefore(time() + 5) //當(dāng)前時間在這個時間前椭符,token不能使用
->set('uid', 30061); //自定義數(shù)據(jù)
//設(shè)置簽名
$builder->sign($signer, $secret);
//獲取加密后的token剩失,轉(zhuǎn)為字符串
$token = (string)$builder->getToken();
var_dump($token);
驗證token
<?php
use \Lcobucci\JWT\Parser;
use \Lcobucci\JWT\Signer\Hmac\Sha256;
include "../vendor/autoload.php";
$signer = new Sha256();
$secret = "suspn@)!*";
//獲取token
$token = isset($_SERVER['HTTP_AUTHORIZATION']) ? $_SERVER['HTTP_AUTHORIZATION'] : '';
if (!$token) {
invalidToken('Invalid token');
}
try {
//解析token
$parse = (new Parser())->parse($token);
//驗證token合法性
if (!$parse->verify($signer, $secret)) {
invalidToken('Invalid token');
}
//驗證是否已經(jīng)過期
if ($parse->isExpired()) {
invalidToken('Already expired');
}
//獲取數(shù)據(jù)
var_dump($parse->getClaims());
} catch (Exception $e) {
//var_dump($e->getMessage());
invalidToken('Invalid token');
}
function invalidToken($msg) {
header('HTTP/1.1 403 forbidden');
exit($msg);
}