我正在尝试在用户成功刷新访问令牌后将用户重定向回其原始请求/数据。
对于每个资源请求,我通过中间件中的 cookie 检查访问令牌:
// The route to access the index page (must be authorized to access)
router.get('/', middlewares.verifyAccessToken(), indexController.indexPage);
当到达 verifyAccessToken() 中间件时,如果访问令牌有效,它将简单地执行 next(),如果无效,它将重定向到 /refresh:
// Access Token verification middleware to access resources
// Continues to the next request in the route if the access token is valid
// Continue to the /refresh route if the access token is expired
exports.verifyAccessToken = (redirect) => (req, res, next) => {
const accessToken = req.cookies.accessToken;
// No access token was even found
// Inform the user of the error and they will have to log back in and generate a new access/refresh token pair
if (!accessToken) {
return res.status(401).json({ message: 'Verification Error: Access Token missing' });
}
// Verify the access token
jwt.verify(accessToken, process.env.ACCESS_TOKEN_SECRET, (err, decoded) => {
if (err) {
// The access token is no longer valid
// Redirect the user to the /refresh route
// The /refresh route will have access to the refreshToken through the cookie on this path
return res.redirect('/refresh');
} else {
// The access token is valid
// Extract some information about the user and pass it onto the next chain in the route
req.decoded = decoded;
next();
}
});
};
但是现在我不知道在 /refresh 路线中该怎么做。 /refresh 路由可以访问刷新令牌,并且我可以成功生成新令牌,但如何让用户返回到原始请求? (在本例中,访问索引页)
在这种情况下,我希望它重定向回链中的下一个路由,即indexPage控制器。
如何在将它们重定向到“/refresh”之前基本上恢复“next()”
有没有更好的方法来解决这个问题?
您可以在重定向到刷新路由之前存储原始请求 URL。成功刷新访问令牌后,您可以将用户重定向回此原始 URL。尝试这样的事情,
exports.verifyAccessToken = () => (req, res, next) => {
const accessToken = req.cookies.accessToken;
// Store the original request URL
req.session.originalUrl = req.originalUrl;
// Your existing verification logic
// ...
// Redirect to the /refresh route if the access token is expired
return res.redirect('/refresh');
};
// handle token refresh
app.get('/refresh', (req, res) => {
// Your token refresh logic
// ...
// Redirect back to the original URL
const originalUrl = req.session.originalUrl || '/';
delete req.session.originalUrl; // Clear the stored URL
return res.redirect(originalUrl);
});