PHP code example of easyswoole / jwt
1. Go to this page and download the library: Download easyswoole/jwt library . Choose the download type require .
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
easyswoole / jwt example snippets
use EasySwoole\Jwt\Jwt;
$jwtObject = Jwt::getInstance()
->setSecretKey('easyswoole') // 秘钥
->publish();
$jwtObject->setAlg('HMACSHA256'); // 加密方式
$jwtObject->setAud('user'); // 用户
$jwtObject->setExp(time()+3600); // 过期时间
$jwtObject->setIat(time()); // 发布时间
$jwtObject->setIss('easyswoole'); // 发行人
$jwtObject->setJti(md5(time())); // jwt id 用于标识该jwt
$jwtObject->setNbf(time()+60*5); // 在此之前不可用
$jwtObject->setSub('主题'); // 主题
$jwtObject->setPrefix('Bearer'); // token前缀(可选)
// 自定义数据
$jwtObject->setData([
'other_info'
]);
// 最终生成的token
$token = $jwtObject->__toString();
// 如果设置了setPrefix将会在生成的token加入对应的前缀,decode的时候会自动截取还原token
// Bearer +token (前缀与token间有一个空格,请注意)
use EasySwoole\Jwt\Jwt;
$token = "eyJhbGciOiJITUFDU0hBMjU2IiwiaXNzIjoiZWFzeXN3b29sZSIsImV4cCI6MTU3MzgzNTIxMSwic3ViIjoi5Li76aKYIiwibmJmIjoxNTczODMxOTExLCJhdWQiOiJ1c2VyIiwiaWF0IjoxNTczODMxNjExLCJqdGkiOiJjYWJhZmNiMWIxZTkxNTU3YzIxMDUxYTZiYTQ0MTliMiIsInNpZ25hdHVyZSI6IjZlNTI1ZjJkOTFjZGYzMjBmODE1NmEwMzE1MDhiNmU0ZDQ0YzhkNGFhYzZjNmU1YzMzMTNjMDIyMGJjYjJhZjQiLCJzdGF0dXMiOjEsImRhdGEiOlsib3RoZXJfaW5mbyJdfQ%3D%3D";
try {
$jwtObject = Jwt::getInstance()->decode($token);
$status = $jwtObject->getStatus();
// 如果encode设置了秘钥,decode 的时候要指定
// $status = $jwt->setSecretKey('easyswoole')->decode($token)
switch ($status)
{
case -1:
echo 'token无效';
break;
case 1:
echo '验证通过';
$jwtObject->getAlg();
$jwtObject->getAud();
$jwtObject->getData();
$jwtObject->getExp();
$jwtObject->getIat();
$jwtObject->getIss();
$jwtObject->getNbf();
$jwtObject->getJti();
$jwtObject->getSub();
$jwtObject->getSignature();
$jwtObject->getPrefix();
$jwtObject->getProperty('alg');
break;
case 2:
echo '验证失败';
break;
case 3:
echo 'token过期';
break;
}
} catch (\EasySwoole\Jwt\Exception $e) {
}