This post will be a simple walkthrough to the access token and refresh token. Grab your seat belt and let's understand about token first.๐
So, what is a token?
Token is a piece of data that carry enough information to work out the process of authenticating a user's identity or authorizing a user to access the resource. For example, when you go through security in an airport, you show your ID to authenticate your identity and they access to the seat.
What is an access token and refresh token? image source: google.com
A refresh token is a long-lived token (a JWT in OAuth2) that is used to renew the access token. When you first receive the access token, you are much likely to get the refresh token as well. Access tokens are short-lived with the expiry duration limited to hours rather than days or months, to prevent the numerous vulnerabilities.
generateTokens(payload){
const accessToken = jwt.sign(payload, JWT_ACCESS_TOKEN_SECRET,{
expiresIn: '1h'
})
const refreshToken = jwt.sign(payload, JWT_REFRESH_TOKEN_SECRET,{
expiresIn: '1y'
})
return {accessToken, refreshToken}
};
Here you can see, the generateTokens function is getting the payload which is the users' ID. The jwt.sign() function is used to generate a unique token using the metadata. There exists an option called โexpiresInโ which defines the time that the received access token and refresh token will be valid for. When the access token expires it can't be used to access intended resources. If an API request with an invalid access token, you'll get an error response as follows:
HTTP/1.1 401 Unauthorized
And if that happens, the client will again have to be authorized and get another access token to continue its work, which leads to the bad user experience. That's where refresh token comes in picture.
Refresh token does not refresh the access token, but once an access token expires, the server verifies the refresh token to generate a new access token for the user. With this access token, the client will be able to continue his work and access the resources. It all happens in background to not interrupt the user. The refresh token is stored in database to get the newly access token.
But what if the refresh token gets expired?
The client will request the refresh token, the server will validate the user, store the refresh token in database and give the response back to the client to update it.
Thanks.โค๏ธ
Resources
For further elaborated reading the following resources can be accessed :
oauth.net/articles/authentication