Token Expiration and Refresh Tokens
You'll learn how to balance security and user convenience by combining short-lived access tokens with longer-lived refresh tokens.
The Security vs Usability Dilemma
With stateless tokens (like JWTs), once issued, they're valid until expiration—you can't "revoke" them easily. If a token is stolen, an attacker has access until it expires. The obvious solution? Make tokens expire quickly. But forcing users to log in every few minutes ruins their experience.
The two-token solution: Use access tokens that expire quickly (minutes to hours) for API requests, paired with refresh tokens that last much longer (days to weeks) but are only used to obtain new access tokens.
How It Works
Think of it like a hotel key card system:
- Access token = your room keycard (expires daily)
- Refresh token = your ID at the front desk (valid for your entire stay)
When your keycard expires, you don't re-check in—you show your ID to get a new keycard.
Your client stores both tokens. When the access token expires (detected via 401 response or checking expiration claim), the client automatically uses the refresh token to request a new access token from a dedicated endpoint. Users stay logged in seamlessly.
Security Benefits
- Reduced attack window: Stolen access tokens are useless after minutes
- Revocation becomes possible: Store refresh tokens in a database; you can invalidate them immediately
- Different security rules: Refresh endpoints can require additional checks (device fingerprinting, IP validation)
Key Takeaway: Short-lived access tokens minimize risk while long-lived refresh tokens maintain user sessions—providing both strong security and good UX through a two-tier token strategy.