Practice & Assessment
Test your understanding of JWT Authentication
Multiple Choice Questions
6A developer does not pass an algorithms option to jwt.verify(). What attack does this enable?
What is the main reason to use an httpOnly cookie instead of localStorage to store a JWT?
What is the purpose of the 'sub' claim in a JWT payload?
A user changes their password. Which JWT invalidation strategy immediately invalidates all their existing access tokens without adding latency to every future request?
What is refresh token reuse detection?
Which JWT claim should you store in a Redis blacklist when a user logs out, and why?
Coding Challenges
1Build a JWT auth middleware
Write an Express middleware function that extracts a Bearer token from the Authorization header, verifies it with jsonwebtoken using HS256 only, attaches the decoded payload to req.user, and calls next(). If the token is missing, return 401. If the token is expired, return 401 with message 'Token expired'. If the token is invalid for any other reason, return 401 with 'Invalid token'. Apply this middleware to a GET /me route that returns req.user. Input: HTTP request with Authorization header. Output: JSON user payload or 401 error. Estimated time: 20–25 minutes.
Mini Project
Stateless Auth API with Access and Refresh Tokens
Build a complete JWT-based auth REST API. Implement: POST /auth/register (hash password, store user), POST /auth/login (verify credentials, issue 15-minute access token via JSON response and 7-day refresh token via httpOnly cookie), POST /auth/refresh (verify refresh token, issue new access token, rotate refresh token), POST /auth/logout (clear refresh token cookie), GET /api/me (protected with JWT middleware, returns user info). Implement token versioning on the user model so POST /auth/logout-all increments the version and invalidates all active tokens. Test all routes with curl showing headers.
