官网 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@)!*";
//设置header和payload,以下的字段都可以自定义
$builder->setIssuer("suspn.com") //发布者
->setAudience("suspn.com") //接收者
->setId("abc", true) //对当前token设置的标识
->setIssuedAt(time()) //token创建时间
->setExpiration(time() + 60) //过期时间
->setNotBefore(time() + 5) //当前时间在这个时间前,token不能使用
->set('uid', 30061); //自定义数据
//设置签名
$builder->sign($signer, $secret);
//获取加密后的token,转为字符串
$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');
}
//验证是否已经过期
if ($parse->isExpired()) {
invalidToken('Already expired');
}
//获取数据
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);
}