Answer the question
In order to leave comments, you need to log in
React, nodejs, jwt - how to do authentication and authorization with refresh token?
Colleagues good day The
question is certainly not new, but still, tell me who did the implementation of the case, the first time I encountered rest globally.
Implementation of authentication authorization and replacement of the token after the time expires!
Thank you in advance
Answer the question
In order to leave comments, you need to log in
You make a request, check the token in the middleware. Throw an error if the time limit has expired.
On the client with this error, you send a refresh token to a separate route.
On it, in the middleware, you check the refresh of the token. If the refresh is valid, send the
client a new pair of accesses and a refresh token. If not, then an access error.
I don't know if it will help you, you can try something like this. And it works, you can check through middlewares or do it, endpoint. On which you can knock, after the expiration of time. Basic example!
const jwt = require('jsonwebtoken');
const secret = process.env.TOKEN_SECRET || 'some other secret as default';
const tokenLife = +process.env.TOKEN_LIFE || 3600;
module.exports = (req, res) => {
const { refreshToken } = req.body;
jwt.verify(refreshToken, secret, (err, decoded) => {
if (err) {
return res.status(401).send('Unauthorised');
}
if (decoded) {
const payload = {
id: decoded.id,
email: decoded.email,
};
jwt.sign(payload, secret, { expiresIn: tokenLife }, (Error, token) => {
if (Error) {
return res.status(401).send('Unauthorised');
}
res.send({
success: true,
accessToken: `Bearer ${token}`,
});
});
}
});
};
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question