我正在尝试在我的快速中间件中配置 token 刷新方法,其中 token 在每次向 API 发出请求时都会进行验证。我将检查 token 是否过期,如果是,我将使用新的过期日期签署一个新 token 。问题是我必须再次发送 token ,但这样做会丢失发送带有响应的 token 的原始请求,并且 API 将不会继续发送到目标端点。
如何发回新的刷新 token 并继续请求?
我的快速中间件来检查 token :
apiRouter.use(function(req, res, next) {
var token = req.body.token || req.query.token || req.headers['x-access-token'];
if (token) {
jwt.verify(token, app.get('superSecret'), function(err, decoded) {
if (err) {
//Here I can check if the received token in the request expired
if(err.name == "TokenExpiredError"){
var refreshedToken = jwt.sign({
success: true,
}, app.get('superSecret'), {
expiresIn: '5m'
});
//Here need to send the new token back to the client and continue with the request
//but if I use return res.... the request don't continue to next()
next();
}else if (err) {
return res.json({ success: false, message: 'Failed to authenticate token.' });
}
} else {
//If no error with the token, continue
next();
};
});
} else {
return res.status(403).send({
success: false,
message: 'No token provided.'
});
}
});
我不知道这是否是最好的方法。
谢谢。
最佳答案
您不能对单个请求向客户端发送两次响应,因此更好的方法是使用实际的 API 响应发送访问 token 。
apiRouter.use(function(req, res, next) {
var token = req.body.token || req.query.token || req.headers['x-access-token'];
if (token) {
jwt.verify(token, app.get('superSecret'), function(err, decoded) {
if (err) {
//Here I can check if the received token in the request expired
if(err.name == "TokenExpiredError"){
var refreshedToken = jwt.sign({
success: true,
}, app.get('superSecret'), {
expiresIn: '5m'
});
request.apiToken = refreshedToken;
next();
}else if (err) {
return res.json({ success: false, message: 'Failed to authenticate token.' });
}
} else {
//If no error with the token, continue
request.apiToken = token;
next();
};
});
} else {
return res.status(403).send({
success: false,
message: 'No token provided.'
});
}
});
然后,当您发送响应时,然后发送带有 token 的响应,您可以通过 request.apiToken 获取该 token 。
但更好的策略是提供客户端刷新 token 并让客户端发出请求以获取刷新 token 。
您可以阅读更多相关信息 here
关于Express 中间件中的 Node.js JWT 刷新 token ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48662639/