【发布时间】:2018-07-17 16:11:07
【问题描述】:
我正在尝试在我的 express 中间件中配置一个令牌刷新方法,该方法在对 api 的每个请求时都会验证令牌。我将检查令牌是否过期,如果是,我将签署一个具有新到期日期的新令牌。问题是我必须再次发送令牌,但是这样做我丢失了发送令牌和响应的原始请求,并且 api 不会继续到目标端点。 如何发回新刷新的令牌并继续请求?
我的快速中间件检查令牌:
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.'
});
}
});
我不知道这是否是最好的方法。
谢谢。
【问题讨论】:
标签: node.js api express jwt token