We have authenticateToken middleware in getpost router. The authenticateToken middleware validates the token.
If the token has expired, the if(err) conditional statement is executed. At this time, the accessToken is issued again through the refreshtoken.
I would like to pass this issued accessToken to the router. console.log(accessToken); How do I fix the code to do this?
this is my code
(index.js)
router.post('/getpost', authenticateToken, async (req, res, next) => {
try {
console.log(accessToken);
} catch (error) {
console.error(error);
next(error); // status 500
}
});
(middleware.js)
exports.authenticateToken = (req, res, next) => {
jwt.verify(token, process.env.ACCESS_TOKEN_SECRET, async (err, user) => {
if (err) {
jwt.verify(
refreshToken,
process.env.REFRESH_TOKEN_SECRET,
async (err, user) => {
if (err) return res.sendStatus(403);
const accessToken = await generateAccessToken(users); // i want to pass this accessToken to router
console.log('accessToken::::', accessToken);
},
);
res.json({accessToken: accessToken});
}
req.user = user;
next();
});
};
function generateAccessToken(user) {
return jwt.sign(user, process.env.ACCESS_TOKEN_SECRET, {expiresIn: '55s'});
}
app.post("/token", (req, res) => {
const refreshToken = req.body.token;
console.log("refreshToken:", refreshToken);
if (refreshToken == null) return res.sendStatus(401);
if (!refreshTokens.includes(refreshToken)) return res.sendStatus(403);
jwt.verify(refreshToken, process.env.REFRESH_TOKEN_SECRET, (err, user) => {
if (err) return res.sendStatus(403);
const accessToken = generateAccessToken({ name: user.name });
res.json({ accessToken: accessToken });
});
});
I think you can do something like this
exports.authenticateToken = (req, res, next) => {
jwt.verify(token, process.env.ACCESS_TOKEN_SECRET, async (err, user) => {
if (err) {
jwt.verify(
refreshToken,
process.env.REFRESH_TOKEN_SECRET,
async (err, user) => {
if (err) return res.sendStatus(403);
const accessToken = await generateAccessToken(users); // i want to pass this accessToken to router
// Adding token to the req object
req.accessToken = accessToken
// Added this
next()
},
);
res.json({accessToken: accessToken});
} else {
req.user = user;
next();
}
});
};
function generateAccessToken(user) {
return jwt.sign(user, process.env.ACCESS_TOKEN_SECRET, {expiresIn: '55s'});
}
You pass token using req object, and get the token in route like this
router.post('/getpost', authenticateToken, async (req, res, next) => {
try {
// Access the token through req object
console.log(req.accessToken);
} catch (error) {
console.error(error);
next(error); // status 500
}
});
Edit: Wrote example based on code in question
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.