Access Tokens vs Refresh Tokens
Access Token :
Access Tokens are used to access routes in a backend server.
Access Token are generated when /login route is hit.
Firstly username or email along with password is extracted from req body.
If user exists with provided username or email and if password is correct, then generate access token and refresh token and send them in cookies in response.
Also store refresh token in database.
To verify access token, get access token from req.cookies or req.header(for android app’s frontend).
Verify it using jwt.verify and ACCESS_TOKEN_SECRET, to ensure that it was generated from this server and is not expired, and find user through _id field, which is in decode payload of refresh token given by jwt.verify, and send that user to next middleware in req.user, if that user exists.
Refresh Token :
If access token expires, user will again have to hit login route, by giving email and password again and again.
So for that a concept called refresh token was introduced, if access denied response comes to frontend due to access token being expired, then frontend should hit a /refresh-access-token route.
This route’s controller extracts incoming refresh token from req.cookies or req.body(for android app’s frontend).
Then verify refresh token through jwt.verify and REFRESH_TOKEN_SECRET, to ensure that it was generated from this server and is not expired.
Then find user with _id field which is in decode payload of refresh token given by jwt.verify.
If user exists then check if the refresh token is same as stored in user document in database.
If, it is same, then generate new access token and refresh token and store new refresh token in database and send both new tokens through cookies in response.