Refresh Token & Access Token

Access Token
Definition: A short-lived token issued by the authorization server to the client after a successful authentication. It is used to access protected resources.
Purpose: Grants access to specific APIs or resources on behalf of the user.
Lifespan: Typically has a short expiry time (e.g., hours or 1 day) to enhance security.
Usage: Sent in the
Authorization
header of an API request, often in the format:Authorization: Bearer <access_token>
Characteristics:
Encodes user-specific data or a reference to it.
Cannot be refreshed once expired; a new one is obtained using a refresh token.
Refresh Token
Definition: A long-lived token issued along with the access token. It is used to obtain a new access token without requiring the user to log in again.
Purpose: Ensures seamless user experience by allowing the client to fetch new access tokens without re-authenticating the user.
Lifespan: Longer than access tokens (e.g., days, weeks, or months) but should still have an expiration for security reasons.
Usage: Sent to the authorization server in a secure channel (e.g., HTTPS) to request a new access token.
POST /oauth2/token Content-Type: application/x-www-form-urlencoded grant_type=refresh_token& refresh_token=<refresh_token>& client_id=<client_id>& client_secret=<client_secret>
Characteristics:
Often stored more securely than access tokens (e.g., in a secure cookie or server-side storage).
If compromised, it can be used to obtain new access tokens, so it should be revoked when no longer needed.
Key Differences
Feature | Access Token | Refresh Token |
Purpose | Access protected resources. | Obtain new access tokens. |
Lifespan | Short (hours or 1 day). | Long (days, weeks, or months). |
Exposure | Frequently exposed in API requests. | Rarely sent over the network. |
Security | Less critical if compromised (short-lived). | More critical if compromised (can generate new access tokens). |
Revocation | Expires automatically. | Can be explicitly revoked. |
Best Practices
Secure Storage:
Store access tokens in memory or a short-lived storage like
sessionStorage
.Store refresh tokens securely, such as in HTTP-only cookies.
Use HTTPS:
- Always send tokens over secure channels to prevent interception.
Implement Token Rotation:
- Rotate refresh tokens after each use to mitigate replay attacks.
Revoke Compromised Tokens:
- Implement mechanisms to revoke access and refresh tokens in case of a breach.
Learn More About Access and Refresh Tokens
For a more detailed explanation, check out this YouTube video by Hitesh Choudhary Sir: @YouTube
Subscribe to my newsletter
Read articles from Akshay Kumar directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
