01. The Core Split: Authentication vs. Authorization
These two terms are constantly confused. They are different boundaries:
| Concern | Question It Answers | Example |
|---|---|---|
| Authentication | ”Who are you?” | Login form verifies email + password |
| Authorization | ”What are you allowed to do?” | Admin panel checks if user has admin role |
Authentication always comes first. You can’t check permissions until you know who’s asking.
02. Stateless vs. Stateful Auth: The Architecture Decision
Your first architectural decision is how the server remembers the user’s identity across requests.
Stateful Sessions (Server-Side)
User logs in
│
▼
Server generates random Session ID: "abc123"
│
├──▶ Stores in Redis: { "abc123": { userId: 42, role: "admin" } }
│
└──▶ Sends to browser as cookie: Set-Cookie: session=abc123; HttpOnly; Secure
Every subsequent request:
Browser sends cookie: Cookie: session=abc123
Server looks up "abc123" in Redis → finds userId 42 → "Welcome, user 42"
Pros:
- Instant revocation — delete the session from Redis, user is logged out immediately
- Server controls session lifetime — no expiration hacks needed
- Simple to implement and debug
Cons:
- Requires a shared session store (Redis) across all server instances
- Horizontal scaling requires every server to reach the same Redis cluster
- Redis becomes a single point of failure for auth
Stateless JWTs (Client-Side)
User logs in → Server creates JWT
Server sends: eyJhbGciOi... (encoded string)
Browser stores: in HttpOnly cookie (NOT localStorage)
Every subsequent request: Browser sends Authorization: Bearer eyJhbGciOi... → Server decodes JWT, verifies signature, reads payload → “Welcome, user 42” (No database lookup needed).
Pros:
- No server-side storage — token is self-contained
- Horizontal scaling works instantly — every server has the same secret key
- Works across domains and microservices
Cons:
- Cannot easily revoke before expiration — stolen token = 2-hour access (or whatever the expiry is)
- Requires token refresh infrastructure to rotate tokens
- Payload is base64-encoded (not encrypted) — anyone can read it (but not forge it)
The Decision Matrix
| Factor | Sessions | JWTs |
|---|---|---|
| Revocation | Instant (delete from Redis) | Difficult (need blacklist or short expiry) |
| Scaling | Requires shared Redis | Scales horizontally with zero coordination |
| Complexity | Lower to implement | Higher (refresh tokens, rotation, blacklisting) |
| Microservices | Harder (central session store) | Natural fit (each service verifies independently) |
| Best For | Traditional server-rendered apps | SPAs, mobile apps, microservices |
Senior Move: The Hybrid Pattern
Use short-lived JWTs (15 min) paired with long-lived refresh tokens (7 days) stored in HttpOnly cookies. The JWT handles authorization on every request. When it expires, the refresh token silently rotates a new JWT without user interaction. If the refresh token is stolen, revoke it server-side and the attacker loses access.
Access Token (JWT): 15 min expiry → Sent with every request
Refresh Token: 7 day expiry → Stored in HttpOnly cookie, used only to get new JWTs
03. JWT Structure Deep Dive
A JWT is three base64url-encoded segments separated by dots:
eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOjQyLCJyb2xlIjoiYWRtaW4iLCJleHAiOjE3MjAwMDAwMDB9.signature
│ │ │
├─ Header ├─ Payload ├─ Signature
│ {"alg":"HS256", │ {"sub":42, │ HMAC-SHA256(
│ "typ":"JWT"} │ "role":"admin", │ header + payload,
│ │ "exp":1720000000} │ secret_key)
│ │ │
│ Algorithm used │ User data + expiry │ Proves token wasn't tampered with
Critical: The payload is encoded, not encrypted. Anyone can decode it and read the data. Never put sensitive information (passwords, SSN, credit card numbers) in a JWT payload. Only put what’s needed for authorization (user ID, role, permissions).
JWT Verification Flow
Tell your AI tool: “Add JWT verification middleware. When a request comes in with an Authorization header, verify the token using the JWT_SECRET environment variable. If valid, attach the user payload to the request. If expired, return 401. If invalid, return 403.”
What happens during verification:
- The server reads the token from the Authorization header
- It uses the JWT_SECRET to verify the signature hasn’t been tampered with
- It decodes the payload (user ID, role, expiration)
- If valid, the request proceeds with user context attached
04. Token Storage: The Security Battlefield
Where you store tokens determines your entire security posture. This is where most AI-generated code gets it wrong.
The Storage Comparison
| Storage | XSS Safe? | CSRF Safe? | Accessibility | Verdict |
|---|---|---|---|---|
localStorage | No — JS can read it | Yes — not sent with requests | Easy | Never for auth tokens |
sessionStorage | No — JS can read it | Yes — not sent with requests | Easy | Never for auth tokens |
HttpOnly Cookie | Yes — JS cannot touch it | No — sent with every request | Limited | Best for access tokens |
Memory (JS variable) | No — cleared on refresh | Yes | Terrible | Never |
The Correct Pattern: HttpOnly + Secure + SameSite
Tell your AI tool: “Set authentication cookies with these security flags:
- httpOnly: true (JavaScript cannot read the cookie)
- secure: true (only sent over HTTPS)
- sameSite: ‘lax’ (not sent on cross-origin requests)
- maxAge: 15 minutes for access token
- path: ’/’ for access token, ‘/auth/refresh’ for refresh token”
Why these flags matter:
- HttpOnly: Prevents JavaScript from reading the cookie (blocks XSS theft)
- Secure: Prevents cookie from being sent over insecure HTTP
- SameSite: Prevents cookie from being sent on cross-origin requests (blocks CSRF)
Why HttpOnly Blocks XSS
Even if an attacker injects malicious JavaScript into your page:
document.cookie→ Only shows non-sensitive cookies (HttpOnly cookies are invisible)localStorage.getItem('token')→ Works, but you should never store tokens there
The rule: Always store auth tokens in HttpOnly cookies, never in localStorage.
05. XSS, CSRF & CSP: The Three Walls
XSS (Cross-Site Scripting)
What it is: An attacker injects malicious JavaScript into your page that runs in other users’ browsers.
How it happens: Unsanitized user input rendered into HTML.
The Vulnerable Pattern:
If a user submits <script>stealCookies()</script> as their name, and you render it directly into HTML, the script executes in every browser that views the page.
The Fix: Always sanitize user input before rendering. Use a library like DOMPurify to strip dangerous HTML tags and attributes.
Tell your AI tool: “Sanitize all user input before rendering it as HTML. Use DOMPurify to strip script tags and event handlers. Apply this to any user-generated content (comments, profile names, search queries).”
CSRF (Cross-Site Request Forgery)
What it is: A malicious site tricks a user’s browser into making requests to your API, automatically attaching their cookies.
How it happens:
<!-- Malicious site: evil-hacker.com -->
<img src="https://api.yourapp.com/account/delete" />
<!-- Browser sends cookie automatically — action executes -->
<form action="https://api.yourapp.com/transfer" method="POST">
<input type="hidden" name="to" value="attacker-account" />
<input type="hidden" name="amount" value="10000" />
</form>
<script>document.forms[0].submit();</script>
<!-- Browser sends cookie automatically — transfer executes -->
The Defense: SameSite Cookies + CSRF Tokens
Defense 1: SameSite Cookie Attribute
Set your session cookie to sameSite: 'lax'. This tells the browser: “Don’t send this cookie on cross-origin POST requests.” Since CSRF attacks rely on the browser automatically attaching cookies, this blocks them.
Tell your AI tool: “Set all session cookies with sameSite: ‘lax’. This prevents CSRF attacks by not sending cookies on cross-origin POST requests.”
Defense 2: Anti-CSRF Tokens
Generate a random token for each user session. Embed it in every form as a hidden field. When the form is submitted, verify the token matches what the server expects. A malicious site can’t guess this token, so their forged requests fail.
Tell your AI tool: “Implement anti-CSRF tokens. Generate a random token per session, embed it in all forms as a hidden field, and validate it on every POST/PUT/DELETE request.”
CSP (Content Security Policy)
CSP (Content Security Policy)
CSP is an HTTP header that tells the browser which sources of scripts, styles, and resources are trusted. Even if an attacker injects a <script> tag, the browser blocks it if the source isn’t in your policy.
What CSP does: Tells the browser which sources of scripts, styles, and resources are trusted. Even if an attacker injects a <script> tag, the browser blocks it if the source isn’t in your policy.
Tell your AI tool: “Add Content Security Policy headers. Allow scripts only from your own domain. Block inline scripts. Block frames embedding your site. Block forms submitting to external sites.”
The Complete Security Headers
Tell your AI tool: “Add these security headers to all responses:
- Content-Security-Policy: restrict script sources to your domain
- X-Content-Type-Options: nosniff (prevent MIME sniffing)
- X-Frame-Options: DENY (prevent clickjacking)
- Strict-Transport-Security: max-age=31536000 (force HTTPS for 1 year)
- Referrer-Policy: strict-origin-when-cross-origin
- Permissions-Policy: disable camera, microphone, geolocation”
Or use a library: Tell your AI tool to “Add helmet middleware for Express.js” — it sets all security headers automatically.
06. Password Hashing: Never Store Plaintext
The rule: Never store passwords in plaintext. Never MD5 them. Never SHA-256 them. Use a purpose-built password hashing algorithm with a salt.
Why Not MD5/SHA-256?
MD5 and SHA-256 are designed to be fast. That’s great for checksums, terrible for passwords. An attacker with a GPU can brute-force 100 billion MD5 hashes per second. A bcrypt hash takes 100ms to verify — making brute-force 10 million times slower.
bcrypt in Practice
Tell your AI tool: “Use bcrypt to hash passwords during registration with cost factor 12. During login, use bcrypt.compare to verify the password against the stored hash. Never store plaintext passwords.”
What bcrypt does:
- Takes a password and adds random salt (unique per user)
- Hashes the password with the salt using a slow algorithm (cost factor 12 = ~100ms)
- Stores the hash (which includes the salt) in the database
- During login, hashes the input password and compares to stored hash
The Registration Flow
Tell your AI tool: “Create a registration endpoint that:
- Validates password is at least 8 characters
- Checks if email already exists
- Hashes the password with bcrypt (cost factor 12)
- Stores email + hash in the database
- Returns success message”
Argon2: The Modern Alternative
Argon2 is newer than bcrypt and designed to resist GPU-based attacks. It’s the recommended choice for new projects.
Tell your AI tool: “Use Argon2id for password hashing instead of bcrypt. Configure with memoryCost: 64MB, timeCost: 3 iterations, parallelism: 4 threads.”
Senior Moves for Passwords
- Never reveal which field is wrong. If login fails, say “Invalid email or password” — not “Email not found” or “Wrong password.” This prevents enumeration attacks.
- Enforce password strength at registration. Minimum 8 characters, check against common password lists (haveibeenpwned API).
- Implement account lockout. After 5 failed login attempts, lock the account for 15 minutes or require CAPTCHA.
- Use bcrypt cost factor 12+. Lower is faster to hash but easier to brute-force. 12 is the modern standard.
07. OAuth 2.0: Social Login Without Seeing Passwords
When users click “Sign in with Google” or “Continue with GitHub,” they’re using OAuth 2.0. Your platform never sees their password — you request permission from the provider.
The Authorization Code Flow
Implementation with Passport.js
Tell your AI tool: “Implement Google OAuth login using Passport.js. Create two routes:
- GET /auth/google — redirects to Google login with profile and email scopes
- GET /auth/google/callback — handles the callback, finds or creates user in database, sets session”
What happens:
- User clicks “Sign in with Google”
- App redirects to Google’s login page
- User logs into Google, approves your app
- Google redirects back to your callback URL with an authorization code
- Your server exchanges the code for an access token
- You use the token to get the user’s profile (name, email, Google ID)
- You find or create the user in your database
- You set a session cookie — user is logged in
Token Refresh Pattern
Tell your AI tool: “Implement silent token refresh. When the access token expires, use the refresh token to get a new one without user interaction. Store refresh tokens in the database.”
Why refresh tokens matter: Access tokens expire after ~1 hour. Without refresh tokens, users would have to re-login every hour. Refresh tokens let you get new access tokens silently.
Senior Moves for OAuth
- Always validate the
stateparameter. OAuth supports astateparameter to prevent CSRF during the handshake. Generate a random state, store it in the session, and verify it on callback. - Never store the provider’s access token. You only need the user’s profile ID and email. The access token is for the provider’s API, not yours.
- Handle account linking. If a user signs up with email first, then later connects Google, link the Google ID to the existing account — don’t create a duplicate.
- Implement token refresh. Access tokens expire (usually 1 hour). Use refresh tokens to get new ones silently. Store refresh tokens in your database, not just in cookies.
08. Role-Based Access Control (RBAC)
Authentication tells you who the user is. Authorization tells you what they can do. RBAC is the standard pattern for implementing authorization.
The Schema
Tell your AI tool: “Create an RBAC (Role-Based Access Control) system with these tables:
- users: id, email, password_hash
- roles: id, name (admin, editor, viewer)
- permissions: id, name (posts:create, posts:delete, users:manage)
- role_permissions: links roles to permissions
- user_roles: links users to roles”
The Middleware
Tell your AI tool: “Create a requirePermission middleware that checks if the authenticated user has a specific permission. If not, return 403 Forbidden. Use it on routes like: app.delete(‘/api/posts/:id’, requireAuth, requirePermission(‘posts:delete’), handler)“
The Hierarchy Pattern
Tell your AI tool: “Implement role hierarchy where admin inherits editor permissions, and editor inherits viewer permissions. A user with role ‘admin’ automatically has all permissions of lower roles.”
How it works:
- Viewer: can read posts
- Editor: can read, create, update posts
- Admin: can read, create, update, delete posts + manage users
Each higher role inherits all permissions from lower roles.
Key Takeaways
| Concept | Mental Model | Senior Insight |
|---|---|---|
| Authentication vs Authorization | Who are you? vs What can you do? | Always auth first, then check permissions |
| Sessions vs JWTs | Server remembers vs Client carries | Use hybrid: short JWT + long refresh token in HttpOnly cookie |
| JWT Structure | Header + Payload + Signature | Payload is encoded not encrypted — never put secrets in it |
| HttpOnly Cookies | JavaScript cannot read them | The only safe place for auth tokens — blocks XSS theft |
| XSS | Injected scripts read your data | Sanitize all user input, use CSP headers |
| CSRF | Malicious site uses your cookies | SameSite cookies + anti-CSRF tokens |
| CSP | Browser’s script allowlist | Blocks inline scripts and untrusted domains |
| Password Hashing | bcrypt with cost factor 12+ | Never MD5/SHA-256 — they’re too fast for brute-force |
| OAuth 2.0 | Provider authenticates, you get a token | Always validate state parameter, never store provider access tokens |
| RBAC | Users → Roles → Permissions | Middleware checks permissions, not just authentication |