Practice & Assessment
Test your understanding of Authentication and Security
Multiple Choice Questions
6Why should a login endpoint compare passwords even when the user email is not found in the database?
What is the purpose of having both access tokens and refresh tokens?
What does helmet() do to your Express application?
Where should JWT refresh tokens be stored on the client?
Why should your app call process.exit(1) if Zod config validation fails at startup?
What does bcrypt's salt rounds parameter control?
Coding Challenges
1JWT Auth Middleware with Role Guard
Implement a complete auth system with two middleware functions: authenticate(req, res, next) that extracts and verifies a Bearer JWT, attaches decoded payload to req.user, and returns 401 for missing/expired/invalid tokens; authorize(...roles) that returns middleware checking req.user.role against an allowed roles array, returns 403 on mismatch. Create three test routes: GET /public (no auth), GET /api/profile (authenticate only), DELETE /api/admin/users (authenticate plus authorize('admin')). Write a test script that calls all three routes with no token, a valid user token, and a valid admin token. Input: JWT_SECRET in environment. Output: correct HTTP status codes for all combinations. Estimated time: 30 minutes.
Mini Project
Secure Auth API with Refresh Tokens
Build a complete authentication API using Express, bcrypt, jsonwebtoken, helmet, and express-rate-limit. Implement: POST /api/register — validate email and password (min 8 chars), hash password with bcrypt (12 rounds), store user in memory or a JSON file, return 201; POST /api/login — verify credentials, return access token (15m) in body and refresh token (7d) in httpOnly Secure cookie; POST /api/refresh — read refresh token from cookie, verify it, issue new access token; POST /api/logout — clear the refresh token cookie; GET /api/me — protected route returning current user info. Apply helmet, a global rate limiter (100 requests per 15 minutes), and a strict auth limiter (5 per hour) on login and register. Validate all inputs with Zod. Load config from environment using a validated config module.
