1.安装
composer require firebase/php-jwt
安装完成后会在vendor目录下生成firebase目录,里面就是jwt的插件包
2.引用封装
在common.php公共文件中封装即可使用
引入JWT类
use Firebase\JWT\JWT;
<?php
// 应用公共文件
use Firebase\JWT\JWT;
/**
* 生成token
* @param string $userId
* @return string
*/
function createJwt($userId = 'zhangsan')
{
$key = md5('zhangsan.com7725@!'); //jwt的签发密钥,验证token的时候需要用到
$token = array(
"user_id" => $userId,
"iss" => "http://www.gouzuopei.com/",//签发组织
"aud" => "孤单的时候狗作陪!", //签发作者
"iat" => time(),//签发时间
"nbf" => time(),//生效时间
"exp" => time()+14400,//过期时间,3600为一小时
);
$jwt = JWT::encode($token, $key,'HS256');//加密,hs256算法
return $jwt;
}
function verifyJwt($jwt = '')
{
$key = md5('zhangsan.com7725@!');//jwt的签发密钥,
try {
$jwtAuth = json_encode(JWT::decode($jwt, new \Firebase\JWT\Key($key,'HS256')));
$authInfo = json_decode($jwtAuth, true);
$msg = [];
if (!empty($authInfo['user_id'])) {
$msg = [
'status' => 1001,
'msg' => 'Token验证通过',
'data'=>$authInfo['user_id']
];
return $msg;
} else {
$msg = ['status' => 1002, 'msg' => 'Token验证不通过,用户不存在'];
}
return $msg;
} catch (\Firebase\JWT\ExpiredException $e) {
echo json_encode([
'status' => 1003,
'msg' => 'Token过期'
]);
exit;
} catch (\Exception $e) {
echo json_encode([
'status' => 1005,
'msg' => 'Token无效'
]);
exit;
}
}
3.使用
//生成token
$token = createJwt('112233');
//验证token
$id = verifyJwt($token);