Beginner LevelAuthentication & Authorization
What is the difference between Access Tokens and Refresh Tokens?
❓ Interview Prompt: Compare short-lived Access Tokens vs long-lived Refresh Tokens, lifetimes, storage rules, and token renewal flows.
Modern authentication architectures use paired tokens to balance security and user experience:
1. Access Tokens:
•
Purpose: Authorizes immediate access to protected API endpoints.
•
Lifetime: Short-lived (5 to 15 minutes).
•
Format: Usually stateless signed JWTs containing user scopes and permissions.
•
Storage: Kept in memory (JavaScript variable or React state) to prevent persistent storage attacks.
2. Refresh Tokens:
•
Purpose: Exchanged at the auth server to obtain new access tokens without forcing the user to re-enter passwords.
•
Lifetime: Long-lived (7 to 30 days).
•
Format: Opaque random strings backed by a database session record.
•
Storage: Stored securely in 'httpOnly, Secure, SameSite=Strict' cookies.
Code Implementation Example
typescript
// Renewing Access Token using Refresh Token
app.post('/api/auth/refresh', async (req, res) => {
const refreshToken = req.cookies.refreshToken; // Read httpOnly cookie
if (!refreshToken) return res.status(401).json({ error: 'No refresh token' });
const session = await db.sessions.findByToken(refreshToken);
if (!session || session.expiresAt < new Date()) {
return res.status(403).json({ error: 'Invalid or expired refresh token' });
}
// Issue new short-lived Access Token
const newAccessToken = jwt.sign({ sub: session.userId }, SECRET, { expiresIn: '15m' });
res.json({ accessToken: newAccessToken });
});💡Token refresh endpoint issuing new short-lived access token.
🎯 Interview Key Takeaway
Short-lived access tokens authorize API requests; long-lived refresh tokens securely renew access tokens without re-login.
#Access Token#Refresh Token#Tokens#Architecture#Beginner
Back to all Authentication & Authorization Questions→