Cookie vs Session vs Token: Master Java Authentication for Interviews
This guide outlines interview focus points, core definitions, and deep analysis of Cookie, Session, and Token (JWT), compares their storage, security, scalability, and cross‑origin support, and provides high‑frequency follow‑up questions, common variants, memory mnemonics, and selection principles for Java authentication.
Interview Focus Points
Basic concept mastery : Interviewer wants to ensure you can define Cookie, Session, Token and understand their role in web authentication, storage location, and mechanisms.
Architecture evolution awareness : Show you know the transition from Cookie+Session to Token and why distributed systems prefer Token.
Practical application ability : Demonstrate ability to choose the appropriate solution for scenarios such as single‑node apps, distributed systems, or mobile clients, and discuss security risks and mitigations.
Core Answers
Cookie is a small piece of data stored by the browser, generated by the server and sent via the Set-Cookie header. Session is server‑side session data linked to a SessionID stored in a Cookie. Token (e.g., JWT) is a stateless credential containing user information that can be self‑verified.
Comparison Overview
Storage location : Cookie – client browser; Session – server memory/Redis; Token – client (localStorage, Cookie).
Security : Cookie – low (easy to steal); Session – higher (server‑side); Token – higher (signature protects tampering).
Cross‑origin support : Cookie – limited by same‑origin; Session – needs SessionID handling; Token – naturally cross‑origin.
Server load : Cookie – none; Session – requires storage; Token – none (stateless).
Scalability : Cookie – moderate; Session – poor without sharing; Token – excellent for distributed systems.
Mobile friendliness : Cookie – poor; Session – poor; Token – good.
Typical scenarios : Cookie – client preferences; Session – traditional monolith authentication; Token – distributed or mobile authentication.
Deep Dive – Cookie
The workflow consists of four stages:
First request : Browser sends request without any Cookie.
Server sets Cookie : Responds with Set-Cookie header containing name=value and optional attributes (Expires/Max-Age, Domain, Path, Secure, HttpOnly, SameSite).
Browser stores : Saves the Cookie in memory or disk based on expiration.
Automatic inclusion : Subsequent requests to the same domain automatically include the Cookie header.
Key attributes and their purposes: Expires/Max-Age: expiration time (e.g., Max-Age=3600 for 1 hour). Domain: scope of the domain (e.g., .example.com). Path: applicable path (e.g., /admin). Secure: sent only over HTTPS. HttpOnly: inaccessible to JavaScript, mitigates XSS. SameSite: controls cross‑site request forgery (e.g., Strict).
Limitations:
Size limit: max 4 KB per Cookie, up to 20 Cookies per domain.
Security: plain text, vulnerable to theft and tampering.
Cross‑origin restrictions due to same‑origin policy.
Added network overhead on every request.
Deep Dive – Session
Workflow steps:
Login request : User submits credentials.
Create Session : Server validates, creates a Session object, generates a unique SessionID, and stores user data in memory, file, database, or Redis.
Return SessionID : Server sends Set-Cookie with SessionID (e.g., JSESSIONID for Java, PHPSESSID for PHP).
Cookie carried : Browser includes the SessionID Cookie in subsequent requests.
Lookup Session : Server retrieves session data using SessionID.
Return data : After validation, business data is returned.
Storage options comparison:
In‑memory (single instance) : Fastest but lost on restart and not scalable.
In‑memory (cluster) : Complex synchronization, generally not recommended.
Sticky Session : Simple but leads to load imbalance and single‑point failure; suitable for small clusters.
Redis : Fast, supports distributed access; recommended for production.
Database : Persistent but slower; used when durability is required.
Limitations:
Server memory pressure under high concurrency.
Poor scalability without external sharing (Redis, etc.).
Cross‑domain handling is cumbersome in front‑end/back‑end separation.
Mobile clients cannot manage Cookies automatically.
Deep Dive – Token (JWT)
Typical flow:
Login request : Client sends credentials.
Generate Token : Server validates and creates a JWT signed with a secret, containing user ID, expiration, etc.
Client storage : Token is stored in localStorage, sessionStorage, or HttpOnly Cookie.
Send Token : Subsequent requests include the token in the Authorization header as Bearer <token>.
Validate Token : Server verifies the signature and extracts user info without any storage lookup.
Return data : Business data is returned after successful validation.
JWT structure:
Header : Declares token type and signing algorithm (e.g., {"alg":"HS256","typ":"JWT"}), Base64‑encoded.
Payload : Contains standard claims (sub, exp, iat) and custom claims (user ID, roles); also Base64‑encoded. Sensitive data should not be placed here because it can be decoded.
Signature : Cryptographic signature of Header and Payload using the server secret, preventing tampering.
Advantages:
Stateless – no server‑side storage, naturally fits distributed systems.
Cross‑origin friendly – not limited by same‑origin policy.
Mobile‑friendly – can be stored directly on the client.
Performance – no session lookup on each request.
Limitations:
Cannot be actively revoked; token remains valid until expiration unless a blacklist is used.
Payload is immutable once issued.
Security relies on client protection; token leakage is risky.
High‑Frequency Follow‑Up Questions
How to handle token leakage and implement active revocation?
Blacklist mechanism.
Short‑lived access token + refresh token.
Version number embedded in token and checked on each request.
Should JWT be stored in Cookie or localStorage?
Cookie (HttpOnly) – protects against XSS, auto‑sent, suitable for web. localStorage – no size limit, flexible, but vulnerable to XSS; requires strict CSP.
How to achieve Single Sign‑On (SSO) with tokens?
Central authentication server issues a token.
Other services validate the token signature.
No need to share session state across services.
Difference between Session and Cookie?
Storage location, security, capacity, dependency.
Common Interview Variants
Why do distributed systems prefer Token over Session?
Explain JWT principles and its pros/cons.
Design a secure user authentication system.
Relationship between OAuth 2.0 and JWT.
Session sharing solutions in distributed environments.
Memory Mnemonics
Cookie = “delivery box” – client‑side, small capacity, sent with every request.
Session = “warehouse” – server‑side, secure but consumes resources, hard to scale.
Token = “passport” – self‑contained, stateless, friendly to distributed systems.
Selection Principles
Monolithic or small system → Session + Cookie.
Distributed / micro‑service architecture → Token (JWT).
Mobile or cross‑origin scenarios → Token is mandatory.
Summary
Cookie is a client‑side container, Session is server‑side state, and Token is a self‑contained credential. Modern distributed architectures favor Token (JWT) because it is stateless, cross‑origin friendly, and scales horizontally. Token revocation requires auxiliary mechanisms such as blacklists or short‑lived tokens. For web applications, storing the token in an HttpOnly Cookie mitigates XSS, while mobile clients should store it locally.
Java Architect Handbook
Focused on Java interview questions and practical article sharing, covering algorithms, databases, Spring Boot, microservices, high concurrency, JVM, Docker containers, and ELK-related knowledge. Looking forward to progressing together with you.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
