Security: Authentication, Authorization & Encryption
JWT deep-dive, OAuth 2.0 flows, RBAC vs ABAC, OWASP Top 10 vulnerabilities, encryption at rest and in transit.
Security: Authentication, Authorization & Encryption
JWT deep-dive, OAuth 2.0 flows, RBAC vs ABAC, OWASP Top 10 vulnerabilities, encryption at rest and in transit.
What you'll learn
- Design security in from the start โ retrofitting is expensive and incomplete
- JWTs: explicit algorithm whitelist, short expiry (15min), HttpOnly cookies for refresh tokens
- RBAC for coarse-grained access + row-level security for resource ownership
- OWASP: parameterize all queries, verify ownership, use bcrypt for passwords
- Encryption: TLS everywhere in transit; AES-256-GCM + envelope encryption at rest
- Secrets management: AWS Secrets Manager / Vault โ never hardcode, never commit
Lesson outline
Security is a property, not a feature
Security cannot be added after the fact. Retrofitting security onto an insecure system is like adding foundations to an already-built house โ enormously expensive and never quite right.
The 2017 Equifax breach exposed 147 million records via an unpatched 6-month-old vulnerability. A 2-minute fix prevented โ a $575M settlement did not.
Threat modeling before implementation
Ask: "Who are my adversaries? What are they trying to do? What is the impact? What is the prevention cost?" Checklists help but cannot replace this thinking.
JWT: how they work and where they fail
JWT = header.payload.signature (base64url). The signature prevents tampering without the secret key. The server verifies the signature โ if valid, trusts the payload.
Algorithm confusion attack: If your server accepts `alg: none`, an attacker removes the signature and the token is accepted. Always explicitly whitelist the algorithm.
Revocation problem: JWTs are valid until expiry โ cannot be invalidated without a blocklist (negates stateless benefit). Solution: short expiry (15 min) + revocable refresh tokens.
HS256 vs RS256: HS256 uses one shared secret (sign and verify). RS256 uses private key (sign) + public key (verify). Use RS256 when multiple services verify tokens.
1import jwt from 'jsonwebtoken';23function generateTokenPair(userId: string, roles: string[]) {4const accessToken = jwt.sign(5{ sub: userId, roles, type: 'access' },6process.env.JWT_SECRET!,7{8algorithm: 'HS256', // Explicitly set โ never allow 'none'ALWAYS explicitly set algorithm โ never let the token specify its own9expiresIn: '15m', // Short-lived access token10issuer: 'api.example.com', // Prevents reuse from other services11audience: 'app.example.com',12}13);1415// Refresh token: opaque random string stored in DB (revocable)16const refreshToken = crypto.randomBytes(32).toString('hex');17return { accessToken, refreshToken };18}1920async function verifyAccessToken(token: string) {Explicit algorithm whitelist prevents algorithm confusion attacks21const payload = jwt.verify(token, process.env.JWT_SECRET!, {22algorithms: ['HS256'], // โ Explicit whitelist โ critical23issuer: 'api.example.com',24audience: 'app.example.com',25});2627// Optional: check revocation list for compromised tokens28const jti = (payload as jwt.JwtPayload).jti;29if (jti && await redis.exists(`revoked:${jti}`)) {30throw new Error('Token revoked');31}3233return payload as jwt.JwtPayload;localStorage is readable by XSS; HttpOnly cookies are not34}3536// Store access token: memory/session storage (not localStorage โ XSS risk)37// Store refresh token: HttpOnly cookie (inaccessible from JS)
OWASP Top 10: the most critical vulnerabilities
- ๐Injection (SQL, Command) โ Never concatenate user input into queries. Always use parameterized queries/ORM.
- ๐Broken Access Control (IDOR) โ Verify resource ownership on every request. UUID IDs prevent enumeration.
- ๐Cryptographic Failures โ MD5/SHA1 broken for passwords. Use bcrypt/argon2. HTTPS everywhere. Encrypt PII at rest.
- โ๏ธSecurity Misconfiguration โ Default credentials, verbose errors, open S3 buckets, permissive CORS.
- ๐XSS โ Sanitize all user output. Use Content Security Policy (CSP) headers.
- ๐SSRF โ Validate and allowlist URLs before server-side fetch.
Three security questions for every PR
Is user input sanitized? Is resource ownership verified? Are credentials stored securely? These three questions catch the majority of OWASP Top 10 vulnerabilities.
Encryption: in transit and at rest
In transit: TLS 1.3 for all external traffic. mTLS for internal service-to-service. Never HTTP โ even internal networks can be compromised.
At rest: Encrypt sensitive DB columns (PII, payment tokens) with AES-256-GCM. Use envelope encryption: a data key (DEK) encrypts data; a key encryption key (KEK) from KMS encrypts the DEK. Rotate KEK without re-encrypting all data.
Password hashing: bcrypt (cost factor 12+) or argon2id. Never MD5, SHA1, or SHA256 for passwords โ designed for speed. A modern GPU tries 10 billion SHA256 hashes/second; bcrypt limits to ~100/second.
Secrets management: Never hardcode secrets or commit .env files. Use AWS Secrets Manager, HashiCorp Vault, or GCP Secret Manager. Rotate automatically.
How this might come up in interviews
Security interviews test threat modeling, not tool memorization.
Common questions:
- How do JWTs work and what are their security pitfalls?
- What is IDOR and how do you prevent it?
- How would you store passwords securely?
- Design auth for a multi-tenant SaaS application.
Strong answers include:
- Mentions algorithm confusion attacks for JWT
- Chooses bcrypt over SHA256 for passwords
- Verifies resource ownership beyond authentication
- Knows the difference between OAuth 2.0 and OIDC
Red flags:
- Stores tokens in localStorage
- Uses MD5 for passwords
- Does not verify resource ownership
- Cannot explain RBAC vs ABAC
Quick check ยท Security: Authentication, Authorization & Encryption
1 / 1
A JWT has `"alg": "none"` in its header. What should your server do?
Key takeaways
- Design security in from the start โ retrofitting is expensive and incomplete
- JWTs: explicit algorithm whitelist, short expiry (15min), HttpOnly cookies for refresh tokens
- RBAC for coarse-grained access + row-level security for resource ownership
- OWASP: parameterize all queries, verify ownership, use bcrypt for passwords
- Encryption: TLS everywhere in transit; AES-256-GCM + envelope encryption at rest
- Secrets management: AWS Secrets Manager / Vault โ never hardcode, never commit
From the books
The Web Application Hacker's Handbook โ Stuttard and Pinto (2011)
Chapter 8: Attacking Access Controls
Understanding how attackers exploit vulnerabilities is the fastest way to design defenses that work. Read this book to understand what you are defending against.
Ready to see how this works in the cloud?
Switch to Career Paths for structured paths (e.g. Developer, DevOps) and provider-specific lessons.
View role-based pathsSign in to track your progress and mark lessons complete.
Discussion
Questions? Discuss in the community or start a thread below.
Join DiscordIn-app Q&A
Sign in to start or join a thread.