Practice & Assessment
Test your understanding of JWT Deep Dive
Multiple Choice Questions
5A JWT payload contains { "sub": "user_123", "role": "admin" }. How can an attacker read this data without knowing the secret?
What does passing { algorithms: ['HS256'] } to jwt.verify protect against?
Which JWT registered claim should be used as a unique identifier when implementing a token blocklist?
Why should refresh tokens use a different secret than access tokens?
Which error should trigger a silent token refresh in a client application?
Coding Challenges
1Build a JWT Auth Middleware with Algorithm Whitelisting
Create an Express middleware function authenticateJWT that: extracts the Bearer token from the Authorization header, verifies it using jwt.verify with { algorithms: ['HS256'] } explicitly set, attaches the decoded payload to req.user on success, returns 401 with { error: 'Token expired' } for TokenExpiredError, and returns 401 with { error: 'Invalid token' } for all other failures. Then create a protected GET /profile route that uses this middleware and returns req.user. Test with a valid token, an expired token, and a token with alg:none. Input: HTTP requests with various Authorization headers. Output: 200 with user payload or 401 with error JSON. Estimated time: 20-25 minutes.
Mini Project
JWT Auth Server with Refresh Token Rotation
Build a complete Express auth server with: POST /auth/register (bcrypt hash, store user in memory), POST /auth/login (verify password, issue 15m access JWT + 7d refresh JWT stored in HttpOnly cookie), GET /auth/me (protected route using authenticateJWT middleware, returns user info), POST /auth/refresh (reads HttpOnly cookie, verifies refresh token with separate REFRESH_SECRET, issues new access token and rotates refresh token), POST /auth/logout (clears the refresh token cookie). All JWTs must be signed with explicit algorithm HS256, verified with algorithms whitelist, and include jti, iat, exp, and sub claims. Return appropriate 401/200/400 status codes throughout.
