I understand how to use JWT tokens for authentication/authorization. However, there is not a specific method call or event that invokes the code to provide a new token at the path "/token" using the refresh token. Please answer, does the code below get called automatically behind-the-scenes by NPM package ‘jsonwebtoken’ when the token expires, or is there a manual way to call this that I am missing in the tutorials?
let refreshTokens = []; //in production use redis or other...
app.post('/token', (req, res) => {
const refreshToken = req.body.token;
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 });
})
})
2
Answers
To clarify, this is more of a communication error. Usually JWT token ecosystems are taught as a server-side process without mentioning that the refresh endpoint is called by the client side from an event like a login form, just like any other server side endpoint. Here is a good example of a complete tutorial of the JWT process. It is simple with that being said.
https://github.com/manosriram-youtube/jwt-auth
The post method you have created will never going to execute automatically because as we know http protocol works on request and response model unit and unless we will not give a request its not going to execute and after giving response it close their connection
read this article it will help you
https://jasonwatmore.com/post/2020/06/17/nodejs-mongodb-api-jwt-authentication-with-refresh-tokens