Access token vs Refresh token

What is access token?

Access token is basically used to verify user if user is logged in or not. this simply stores a string, which contains info which user passed in it like email, username, etc.

Access token has a smaller life span. now small means ... umm it might be different for you and me. for me it can be 1 or 2 days, for you it may be 1 or 2 hours.

Access token has values encrypted, and for that, you can many tools, but one of the famous one is Json Web Token (JWT).

5 Lessons Learned Connecting Every IdP to OIDC - Pomerium

Now WTF is this refresh token?

Refresh token is like 'Sundar lal' from famous indian TV serial, 'Tarak Mehta Ka Ooltah Chasmah'. So the job of refresh token is to generate new access token, as soon as the old one expires.

Refresh token has a longer life than access token.(I think, it got blessing from indian moms)

Refresh tokens are stored in database, but access tokens aren't. Respect++.

How to generate access and refresh token?

For generating access and refresh token, something unique about an object is needed. Lets suppose, we're saving some users data in MongoDB's database, which automatically gives us an unique ID(_id). Now, we'll pass this ID and find the user first.

Now, if we've the user, then make a function call to generate access and refresh token, which return JWT signed values and takes three 3 parameters:

  1. what all do you want to encrypt?

  2. what is your access token secret?

  3. how much is your access token expiry?

Same for refresh token. Here's a sample:

Now the user has a refresh token, and our database has a refresh token. So if we need to verify a user, we just compare both the refresh tokens, and once checked, we generate a new access token, and now user can use website smoothly, leaving behind fear of account security!

Access token is stored in cookie and Refresh token is stored in database!

Huge shoutout to Hitesh chaudhry sir! He motivated us to write a blog, and i must, after watching his video and writing a blog, no one can beat you in backend!

Link to his channel: https://www.youtube.com/@chaiaurcode

Sir sorry for bad screenshot and light mode(ifkyk) ๐Ÿ˜‚

22
Subscribe to my newsletter

Read articles from Ashutosh Kumar (Ashu) directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Ashutosh Kumar (Ashu)
Ashutosh Kumar (Ashu)