一、通过 composer 命令安装JWT
在项目根目录执行 composer 命令
composer require firebase/php-jwt
二、使用JWT
(1)生成Token
# JWT参数
$token = [
'iss' => request()->domain(), // 签发者网址
'aud' => $_SERVER['REMOTE_ADDR'], // jwt所面向的用户
'iat' => time(), // 签发时间
'exp' => time() + 600, // 过期时间(10分钟)
'data' => array( // 参数可以根据需求添加
'id' => 1
)
];
$jwt = new \Firebase\JWT\JWT();
$key = 'awesafqewrxfasfd'; // 加密的Key
$token = $jwt->encode($token, $key);
(2)解析Token
$token = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJodHRwOlwvXC93d3cuY2VzaGkuY29tIiwiYXVkIjoiMTI3LjAuMC4xIiwiaWF0IjoxNjM4NTEyNTU2LCJleHAiOjE2Mzg1MTMxNTYsImRhdGEiOnsiaWQiOjF9fQ.P3Zpy1Xfw5wAZDQIG7D3muUyuWKULD357MJ5-ovDFs0";
$JWT = new \Firebase\JWT\JWT();
$key = 'awesafqewrxfasfd'; // 加密的Key
try {
$JWT->$leeway = 60;//当前时间减去60,把时间留点余地
$token = $JWT->decode($token,$key, ['HS256']); //HS256方式,这里要和签发的时候对应
} catch(\Firebase\JWT\SignatureInvalidException $e) {
json(array('code' => 5,'msg' => '签名不正确'))->send();
exit;
}catch(\Firebase\JWT\BeforeValidException $e) {
json(array('code' => 5,'msg' => '签名还未生效'))->send();
exit;
}catch(\Firebase\JWT\ExpiredException $e) {
json(array('code' => 5,'msg' => 'token已过期'))->send();
exit;
}catch(\Firebase\JWT\Exception $e) {
json(array('code' => 5,'msg' => '请重新获取Token'))->send();
exit;
}catch(\UnexpectedValueException $e) {
json(array('code' => 5,'msg' => $e->getMessage()))->send();
exit;
}
# 疑似窃取用户Token攻击行为:请求的客户端ip已经改变, 拒绝请求
if($token->aud !== $_SERVER['REMOTE_ADDR']){
json(array('code' => 5,'msg' => '请求的客户端ip已经改变, 拒绝请求'))->send();
exit;
}
# 调用参数
$id = $token->data->id;
|