How to look at access and refresh tokens

I was learning backend and wanted to use the JWT authentication methodologies due to which I came across this double token analogy for user authentication, after learning about it I thought maybe I should write down my thought process that may help someone in the near future.

So first, what are these tokens exactly?

These tokens are strings which have data garbled up in them so that no one except the one with the secret key can decode it.

Let me show you a fun drawing

Here notice if we change the "Key" then the output will be different, that way we only need to keep our "Key" a secret and then we can hide any data into that garbled output string as long as we know what algorithm is used and more importantly what is the secret key, then we can just push the encoded string into the "machine" along with the "key" and get the original data out of it.

You can check out this website to experience the process yourself.

Now you know tokens, but how are they used ?

Whenever the user logs in for the first time a new set of these two tokens are generated with access token having a comparitively shorter expiry period than the refresh token and then the refresh token gets stored in the database while the access token along with the refresh token are passed as cookie to the original request and get stored on the user side.

Now whenever we want to secure a route(meaning if we want a valid user on the route) then we can simple read the access token from the request and only we know the secret key that was used to make it, only we can decode and verify if the user is the one we have in our database, and only then allow the request to proceed.

But why two tokens with different expiries ?

First lets discuss why we have given short expiry to the access token,

We take this step because its generally safer to authenticate the user for a short period so that he/she can do whatever was they wanted to do and then log out automatically to prevent unauthorized access in the future.

Now when the access is expired we don't want user to go through the hassle of entering the password again, and this is the moment where the role of refresh token comes in,

The user in this situation requests to a certain endpoint which will verify whether the refresh token carried by the user is correct or not, and if its correct then the server generates new set of tokens which are then passed to the user and also the refresh token in the databse is replaced with the new one,

Now the user can visit any secured route again till the access token expires.