ReviseAlgo Logo

Authentication

JWT

Learn JSON Web Tokens in Next.js authentication, what belongs in a token, and how to avoid common session security mistakes.

## 1. Learning Objectives By the end of this lesson, you will be able to explain JWT structure, decide what claims belong in a token, compare JWT sessions with database sessions, and identify common JWT security risks. Difficulty: Intermediate. ## 2. Prerequisites - Authentication basics. - Cookies and HTTP headers. - Server-side authorization. ## 3. Overview A JSON Web Token is a signed token containing claims about a subject. In web apps, JWTs are often used to represent session or authorization state, but they must be handled carefully because they can outlive server-side changes unless invalidation is designed. ## 4. Why This Topic Matters JWTs are common in Next.js apps, APIs, and OAuth flows. Misusing them can leak sensitive data, create hard-to-revoke sessions, or make authorization depend on stale claims. ## 5. Real-World Analogy A JWT is like a sealed badge. Guards can inspect the badge and verify the seal, but if the badge says too much or is valid too long, losing it becomes dangerous. ## 6. Core Concepts | Concept | Meaning | |---|---| | Header | Token metadata such as signing algorithm. | | Payload | Claims such as subject, issuer, audience, and expiry. | | Signature | Cryptographic proof the token was issued by a trusted server. | | Claim | A named piece of token data. | | Expiry | Time after which the token should no longer be accepted. | ## 7. Syntax & API Reference JWT shape:
Example claims:
## 8. Visual Diagram
## 9. Live Example - Full Working Code
What just happened? Authorization checks use token claims, but still verify expiry before trusting them. ## 10. Interactive Playground Try this: - Decode a sample JWT payload. - Remove sensitive fields from the payload. - Add expiry checks before authorizing a request. ## 11. Common Mistakes | Mistake | Why It Happens | Correct Approach | |---|---|---| | Storing secrets in JWT payload | JWT payloads are easy to decode. | Store only non-sensitive claims. | | Long-lived tokens without revocation | Stateless tokens feel convenient. | Use short expiry, rotation, or database sessions. | | Trusting role claims forever | Roles change after token issue. | Refresh claims or check critical permissions server-side. | ## 12. Best Practices - Keep JWT payloads minimal. - Store web session tokens in secure, HTTP-only cookies. - Use short lifetimes for high-risk tokens. - Re-check critical permissions against server data. - Rotate secrets carefully and plan invalidation. ## 13. Browser Compatibility | Feature | Browser Impact | Notes | |---|---|---| | Cookie storage | Broad support | Prefer HTTP-only secure cookies for sessions. | | Bearer token headers | Standard HTTP | Common for API clients. | | Token verification | Server-side | Browser should not be the security authority. | ## 14. Interview Questions **Easy:** What are the three parts of a JWT? Answer: Header, payload, and signature. **Medium:** Is JWT payload data encrypted by default? Answer: No. It is encoded and signed, so do not put secrets in it unless using an encryption scheme. **Hard:** Why are database sessions sometimes safer than JWT sessions? Answer: Database sessions can be revoked or updated centrally, while stateless JWTs may remain valid until expiry. ## 15. Debugging Exercise Bug report: "A demoted admin can still access admin pages for an hour." Solution The JWT likely contains stale role claims. Shorten token lifetime, refresh claims, or re-check sensitive permissions against the database. ## 16. Practice Exercises - Easy: Identify claims in a decoded JWT. - Medium: Write an expiry check. - Hard: Design a token refresh and revocation strategy for admin roles. ## 17. Scenario-Based Challenge A mobile API needs bearer tokens, but the web dashboard uses cookies. Should both use the same storage strategy? Walkthrough No. Browser sessions usually prefer secure HTTP-only cookies; mobile/API clients often use bearer tokens with careful storage, expiry, and rotation. ## 18. Quick Quiz 1. Are JWT payloads secret by default? Answer: No. 2. What claim usually identifies the user? Answer: `sub`. 3. What claim controls expiration? Answer: `exp`. 4. Can JWTs be hard to revoke? Answer: Yes. 5. Should critical authorization be blindly trusted from stale tokens? Answer: No. ## 19. Summary & Key Takeaways - JWTs are signed claim containers. - Payloads are readable, so keep them minimal. - Expiry and revocation strategy matter. - Cookies are often safer for browser sessions. - Re-check high-risk permissions server-side. ## 20. Cheat Sheet | Need | JWT Guidance | |---|---| | User identifier | Use `sub` | | Secret data | Do not store in payload | | Session expiry | Use `exp` | | Admin authorization | Re-check server-side | | Browser session | Prefer secure HTTP-only cookie | ## 21. Further Reading - Auth.js Docs: Session strategies. - JWT RFC 7519. - OWASP: JSON Web Token cheat sheet. ## 22. Next Lesson Preview Next, you will learn middleware/proxy route gating for coarse authentication checks.