Access Token And Refresh Token
The access token and refresh token and most commonly used technique for authentication. So let discuss more about this
What is access token ?
Access Tokens are short-lived tokens used to authenticate users. When a user logs into a web page, we set the access token in their cookies. Since access tokens are short-lived, they expire after a specific time set by the backend developer.
Why access token are short-lived tokens ?
There is a possibility of access token leaks, and if your access token leaks, someone else can use your account without logging in by setting the access token in their cookies. However, since the access token is a short-lived token, it will expire, and the user will be logged out.
What is Refresh Token ?
A refresh token is a long-lived token used to obtain a new access token without requiring the user to log in again.
How refresh token work ?
When the access token expires, the refresh token can be sent to the authentication server to request a new access token. This process helps maintain a seamless user experience by allowing continuous access without frequent logins. Refresh token are stored securely and have a longer expiration time compare to access tokens.
Code to generate access token and refresh token:
Here we are using JSON Web Tokens (JWT) to generate the token. JWT contains two methods: one to generate the token and another to verify the token.
- Generate the token using
jwt.sign()
jwt.sign(
{
_id:this._id,
email:this.email,
username:this.username,
fullname:this.fullname
},
process.env.ACCESS_TOKEN_SECRET,
{
expiresIn:process.env.ACCESS_TOKEN_EXPIRY
}
)
It accepts three parameters Payload, Secret Key and Expiry Time
Verify the token using
jwt.verify()
jwt.verify(token, process.env.ACCESS_TOKEN_SECRET)
It accepts Token and Secret Key.
I am very thankful to Hitesh Choudhary for explaining the concept in such an easy way in #chai-aur-backend. Your clear and concise explanations have made a significant difference in my understanding. Thank you!
Subscribe to my newsletter
Read articles from Himanshuraj Tiwari directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by