DEV Community

Discussion on: Build a Robust JWT Auth System in Node.js: Access and Refresh Token Strategy

Collapse
 
samintunnus profile image
Sami

There is couple things that confuses me:

Refresh token is hashed and saved to database, in the UserSchema.methods.generateRefreshToken.

In the authentication middleware module.exports.requireAuthentication, accestoken is taken from the headers, decoded and attached to the request.

But then for the logout you are saying: "To logout a user, we delete the Access Token (attached in req object by authentication middleware) from the user's record in the database." At which point is the access token saved to the user's record in the database?

And also after that you are saying: "This will cause authentication middleware to invalidate requests that contain this access token.". I can't see anything like that in the authentication middleware. Isn't it in the authentication middleware only looking at the access token in the request headers? And it will only fails if the jwt.verify fails and nothing related to the saved tokens in database?

What am I missing there?

And to add to the confusion, in the module.exports.refreshAccessToken you are finding user with the stale access token, but isn't those tokens saved in the user tokens suppose to be the refresh tokens? Event the const is named as a userWithRefreshTkn.

const userWithRefreshTkn = await User.findOne({
_id: decodedRefreshTkn._id,
"tokens.token": staleAccessTkn,
});

And there you are saying: "6. Remove stale access token from user's record." But I can't find the point where was the access token saved to user's record?

Looks to me you have mixed up access token and refresh token in your head at some point?

Collapse
 
smitterhane profile image
Smitter

Thanks for pointing out, actually in early stage of the source code, access token was being saved to the database on user sign up. And authentication middleware will test for a match between the access token in the request header versus the one in the DB.
The problem with this method is that it beats the logic of stateless authenication where there should be no DB lookups in the authentication middleware. So I changed the source code to depict pure stateless authentication and forgot to change some parts of the article like you have mentioned.

I shall update the article to 100% confer with what the source code in github is doing; answering "the why" and "how".

Collapse
 
harsh9o9 profile image
Harsh Bhardwaj

Could you kindly verify if the article is current? I've noticed some inconsistencies between the code mentioned and the code available in the associated GitHub repository.

Thread Thread
 
smitterhane profile image
Smitter

Hi Bhardwaj, as of Aug 2024, the article is up to date and in sync with the source code in github repo. Apologies for inconsistencies(that are now fixed)