JWT & Session Auth: Deep Dive
Master both JWT and session-based authentication by implementing them from scratch in Node.js. By the end, you will have built a secure auth system with login, token refresh, role-based access, and session management.
Course Content
6 modules · 30 lessonsAuthentication Fundamentals
Understand the difference between authentication and authorization, and explain why stateless vs stateful auth matters in API design.
authentication vs authorization: what is the actual difference
authentication definition, authorization definition, identity vs permission, real-world analogies, common misconceptions, HTTP context
stateful vs stateless authentication: how each approach works
stateful session auth, stateless token auth, server memory vs client storage, scalability tradeoff, cookie vs header, JWT overview
how HTTP cookies work for auth
Set-Cookie header, cookie attributes, HttpOnly flag, Secure flag, SameSite policy, cookie lifecycle, CSRF exposure
Bearer tokens and the Authorization header explained
Authorization header syntax, Bearer scheme, token extraction in middleware, localStorage vs memory storage, XSS risk, header vs cookie comparison
password hashing with bcrypt: why plain storage is catastrophic
plaintext password risks, one-way hashing, bcrypt algorithm, salt rounds, bcrypt.hash, bcrypt.compare, timing attacks, cost factor tuning
JWT Deep Dive
Decode, sign, and verify JWTs manually and with jsonwebtoken, then identify the exact security pitfalls that trip up most developers.
JWT structure explained: header, payload, signature decoded
JWT three-part structure, base64url encoding, header alg and typ fields, payload claims, registered claims, signature generation, dot separator
signing and verifying JWTs with jsonwebtoken in Node.js
jsonwebtoken library, jwt.sign options, jwt.verify, secret key management, TokenExpiredError, JsonWebTokenError, synchronous vs async sign
JWT expiry and refresh token strategy
short-lived access tokens, long-lived refresh tokens, refresh token rotation, token family tracking, silent refresh, refresh endpoint implementation
JWT security pitfalls: algorithm confusion and none attack
alg:none attack, algorithm confusion RS256 vs HS256, explicit algorithm whitelisting in verify, key confusion vulnerability, CVE examples, secure defaults
JWT revocation strategies: blocklist and short TTL tradeoffs
stateless revocation problem, token blocklist in Redis, jti claim, logout implementation, short TTL as revocation substitute, hybrid approaches
Session-Based Authentication
Build server-side session auth using express-session, back it with Redis, and implement secure logout and session fixation protection.
how server-side sessions work in Express
express-session setup, session store mechanics, session ID cookie, req.session object, session middleware configuration, secret signing of session ID
backing sessions with Redis using connect-redis
default MemoryStore limitations, connect-redis setup, RedisStore configuration, session TTL in Redis, production readiness, session key naming
session fixation attacks and how to prevent them
session fixation definition, attack scenario, regenerate on login, req.session.regenerate, session ID rotation, why pre-login sessions are dangerous
secure session logout and session destruction
session destroy vs session clear, req.session.destroy, clearing the session cookie, logout redirect, garbage collection, destroy callback error handling
session middleware for route protection in Express
requireAuth middleware pattern, req.session.userId check, role-based middleware, redirect vs 401 response, middleware chaining, reusable guard functions
OAuth 2.0 and Third-Party Auth
Understand the OAuth 2.0 authorization code flow, implement Google sign-in using Passport.js, and handle OAuth tokens correctly in your backend.
OAuth 2.0 authorization code flow step by step
OAuth roles, authorization code flow, redirect URI, authorization code exchange, access token, refresh token, PKCE overview, state parameter
implementing Google sign-in with Passport.js
passport-google-oauth20 setup, GoogleStrategy configuration, serializeUser, deserializeUser, OAuth callback route, profile data extraction
what OpenID Connect adds on top of OAuth 2.0
OIDC vs OAuth 2.0, ID token, UserInfo endpoint, OIDC scopes, JWT ID token structure, nonce parameter, profile claims
handling OAuth access tokens and scopes in your backend
OAuth access token usage, scope definition, scope validation, token storage for API calls, token expiry handling, refreshing OAuth tokens, minimal scope principle
linking OAuth accounts to existing email-password accounts
account linking strategy, email deduplication, merging OAuth and local accounts, security risks of auto-linking, confirmation flow, multi-provider support
Role-Based Access Control
Design and implement RBAC systems that scale from simple role checks to permission-based policies, and avoid the common authorization mistakes that create privilege escalation vulnerabilities.
RBAC design: roles, permissions, and resource ownership
RBAC definition, role hierarchy, permission granularity, resource ownership model, flat vs hierarchical roles, ABAC comparison, real-world role design
implementing permission middleware in Express
permission check middleware, hasPermission helper, role-permission mapping, middleware factory pattern, combining auth and authz middleware, error response consistency
resource ownership checks: can this user edit this post
ownership verification pattern, database lookup in middleware, param-based ownership, separating ownership from admin override, async middleware, race condition awareness
storing roles in JWT claims vs database lookups
JWT role claims, stale role problem, database role lookup on each request, hybrid approach, role change propagation, token revocation for role changes
common RBAC mistakes that cause privilege escalation
missing authorization checks, IDOR vulnerabilities, mass assignment, trusting client-supplied roles, horizontal vs vertical privilege escalation, security testing
Security Hardening and Production Auth
Harden your auth system against CSRF, brute force, and token leakage, and apply the production security patterns used in real-world APIs.
CSRF attacks and how SameSite cookies prevent them
CSRF attack mechanism, cross-site request, SameSite=Strict vs Lax vs None, Double Submit Cookie pattern, CSRF token header, Origin header validation
rate limiting login endpoints to prevent brute force attacks
brute force attack definition, express-rate-limit setup, per-IP limiting, per-account limiting, progressive delays, rate limit headers, Redis rate limit store
HTTPS, HSTS, and secure headers for auth endpoints
HTTPS requirement for auth, HSTS header, helmet.js setup, Content-Security-Policy, X-Frame-Options, secure cookie prerequisite, HSTS preload
logging auth events without leaking sensitive data
auth event logging, what to log, PII in logs, token logging danger, structured logging, log levels, SIEM integration, audit trail requirements
auth architecture checklist: what a production system needs
production auth checklist, secret rotation, token expiry strategy, account lockout, audit logging, dependency updates, penetration testing, security headers review
