我正在使用Node.js和Express制作API Server。
我也为身份验证用户使用了JWT令牌身份验证。
如果令牌已过期,那么我的情况就在这里。
(Backend) Middleware detect expired
(Frontend) Receive token is expired
(Fronend) Refresh token request to backend
(Backend) Verify token is valid and if it expired, sign new token(with old token's payload) and response it to frontend
在4号,我的代码在这里。
try {
const token = req.headers.authorization.split(' ')[1];
jwt.verify(token, SECRET, (err, decoded) => {
if(err.name === 'TokenExpiredError') {
const payload = jwt.verify(token, SECRET);
const userid = payload.userid;
const is_admin = payload.is_admin;
const refreshToken = jwt.sign({
userid: userid,
is_admin: is_admin
}, SECRET, {
algorithm: 'HS256',
expiresIn: '10m'
})
res.status(200).json({status: true, token: refreshToken});
}
else if(err) {
res.status(401).json({status: false, result: "Invalid token"});
}
})
} catch(e) {
//console.log(e);
res.status(401).json({status: false, result: "Token does not exist"});
}
Run Code Online (Sandbox Code Playgroud)
运行之后,抛出的错误行const payload = jwt.verify(token, SECRET);。
因为如果令牌已过期,则会引发TokenExpiredError错误。
我想解码令牌并提取过期令牌的有效载荷。
但是在中verify(),没有有关有效负载的信息。
于是我看了文件,找到了一些有趣的方法decode()。
但是它提到不要使用decode(),因为它不会检查签名是否正确。
关于提取过期令牌的有效负载有什么解决方案吗?
谢谢。
您可以将选项设置ignoreExpiration为true,以避免在令牌过期时收到此错误(此时您已经知道了),然后获取有效负载:
if(err.name === 'TokenExpiredError') {
const payload = jwt.verify(token, SECRET, {ignoreExpiration: true} );
// your code
}
Run Code Online (Sandbox Code Playgroud)
现在,您可以确定令牌有效,但已过期。
| 归档时间: |
|
| 查看次数: |
2718 次 |
| 最近记录: |