I'm using Node.js and Express to deal with JWT Auth. First of all, every time a user is created and verified, I'm storing a refresh token
inside User
collection:
const refreshToken = await jwt.sign({ userId: decoded.user }, process.env.JWT_Refresh_Key);
const user = await User.updateOne({ _id: mongoose.Types.ObjectId(decoded.user) }, { refresh_token: refreshToken, status: true });
A JWT Access Token is generated after a successful Login (expires after 15min):
const token = await jwt.sign(
{ email: user.email, userId: user._id, role: user.role },
process.env.JWT_Key,
{ expiresIn: '15m' });
res.status(200).json({success: true, token: token});
Then access token
is stored in localStorage
to be handled by Angular Http Interceptor and auth methods. After 15min, the token
will be invalid for handling requests, so I need to use the refresh token
stored on the database.
Refresh method is being called on AuthService.ts
:
export class AuthService {
constructor(private http: HttpClient){}
refreshToken(token: string) {
this.http.post<{token: string, expiresIn: number, name: string}>(`${BACKEND_URL}/refreshtoken`, {token: token})
.subscribe((data) => {
const expiresAt = moment().add(data.expiresIn, 'second');
localStorage.setItem('token', data.token);
localStorage.setItem('expiration', JSON.stringify(expiresAt.valueOf()));
});
}
}
//route
router.post('/refreshtoken', user.refreshToken);
//controller user.js
exports.refreshToken = async(req, res, next) => {
// I need to store and call 'old_refreshtoken' where??
const user = await User.findOne({ refresh_token: old_refreshtoken });
if (user) {
const newToken = await jwt.sign(
{ email: user.email, userId: user._id, role: user.role },
process.env.JWT_Key,
{ expiresIn: '15m' });
res.status(200).json({success: true, token: newToken, expiresIn: 900, name: user.name});
} else {
res.status(401).json({success: false, message: 'Autenticação falhou.'});
}
};
How can I use my refresh token
(database) to generate a new access token
?
I'm not sure how to store a refresh token
on client-side (Angular) to compare to refresh token
stored on the database.