Intermediate LevelREST APIs & Web Services
How do HttpOnly, SameSite, and Secure cookie flags protect JWT tokens from XSS and CSRF?
❓ Interview Prompt: Compare storing JWTs in `localStorage` (vulnerable to XSS) vs `HttpOnly` `SameSite=Strict` `Secure` cookies (protected against XSS & CSRF).
Storing JWTs in browser 'localStorage' exposes them to theft via Cross-Site Scripting (XSS) scripts:
Secure Cookie Defense:
Store JWTs in browser cookies configured with three mandatory security flags:
1
'HttpOnly': Prevents client-side JavaScript ('document.cookie') from reading token, completely blocking XSS token theft!
2
'Secure': Forces cookie transmission ONLY over encrypted HTTPS.
3
'SameSite=Strict' or 'Lax': Blocks browser from sending cookies on cross-site forgery requests, mitigating CSRF attacks!
Code Implementation Example
http
Set-Cookie: jwt=eyJhbGciOiJIUzI1...; Path=/; Secure; HttpOnly; SameSite=Strict; Max-Age=900💡HTTP Set-Cookie header applying HttpOnly, Secure, and SameSite=Strict flags.
🎯 Interview Key Takeaway
Store authentication JWTs in HttpOnly, Secure, SameSite=Strict cookies to protect against XSS and CSRF attacks.
#Cookies#HttpOnly#SameSite#CSRF#XSS#Intermediate
Back to all REST APIs & Web Services Questions→