Skip to main content
Authentication Systems Tutorial
CHAPTER 07 Intermediate

JWT Authentication Explained

Updated: May 14, 2026
30 min read

# CHAPTER 7

JWT Authentication Explained

1. Introduction

In the previous chapter, we established the theory of Token-Based Authentication. However, "Token" is a generic term. In modern web development, when we talk about tokens, we are almost exclusively referring to the industry standard: JSON Web Tokens (JWT). In this chapter, we will dissect the anatomy of a JWT, understand how cryptographic signatures guarantee its integrity, and explore the critical relationship between Access Tokens and Refresh Tokens.

2. Learning Objectives

By the end of this chapter, you will be able to:
  • Define what a JSON Web Token (JWT) is.
  • Break down the three structural components of a JWT (Header, Payload, Signature).
  • Understand how a Digital Signature prevents token tampering.
  • Explain the security necessity of short-lived Access Tokens.
  • Explain the role of long-lived Refresh Tokens.

3. Beginner-Friendly Explanation

Imagine a VIP Concert Ticket.
  1. 1. The Header: The branding at the top of the ticket. It simply states, "This is a Ticket, and it uses a standard barcode."
  1. 2. The Payload: The actual information written on the ticket. "Admit One: John Doe. Seat: Section A, Row 4. Date: Friday 8 PM."
  1. 3. The Signature: The holographic, unforgeable stamp applied by the ticketing agency.

If John takes a pen and crosses out "Row 4" and writes "Front Row," the ticket details (Payload) have changed. But when he hands the ticket to the usher, the usher scans the holographic stamp (Signature). The scanner immediately detects that the ticket was tampered with after the stamp was applied, and the usher kicks John out.

A JWT works exactly the same way. It carries readable JSON data, secured by an unforgeable digital signature.

4. The Anatomy of a JWT

A JWT is a long string of characters separated by exactly two periods (.). It looks like this: xxxxx.yyyyy.zzzzz

It consists of three parts, all Base64Url encoded:

  1. 1. Header (xxxxx): Contains metadata about the token. Usually just two properties: the type of token ("typ": "JWT") and the hashing algorithm being used (e.g., "alg": "HS256").
  1. 2. Payload (yyyyy): Contains the actual "Claims" (the data). This is a JSON object where you store the user_id, the user's role, and standard fields like exp (Expiration Time) and iat (Issued At time).
*Warning:* This is NOT encrypted. Anyone can decode and read this JSON.
  1. 3. Signature (zzzzz): The cryptographic security seal. The server takes the encoded Header, the encoded Payload, and a secret server password, and runs them through the HMAC SHA256 algorithm.

5. How the Signature Prevents Tampering

If a malicious user decodes their JWT, changes the Payload from {"role": "user"} to {"role": "admin"}, and sends it back to the server, why doesn't it work?

Because when the server receives the token, it takes the newly altered Payload, combines it with its secret server password, and calculates the math to generate a *new* Signature. It then compares this new Signature to the Signature attached to the token. Because the Payload changed, the math results in a completely different Signature. They don't match. The server instantly knows the token was tampered with and rejects it with a 401 Unauthorized.

6. Access Tokens vs. Refresh Tokens

If a JWT is stolen by a hacker (e.g., via a malicious browser extension), the hacker can use that JWT to impersonate the user perfectly. Because JWTs are stateless, the server cannot easily "cancel" or "delete" a specific JWT once it is issued.

To mitigate this massive security risk, the industry uses a two-token system:

  1. 1. Access Token (Short-Lived): This is the JWT the frontend uses for every API request. For security, it has a very short expiration time (exp), usually 15 minutes. If a hacker steals it, they only have 15 minutes of access before the token dies.
  1. 2. Refresh Token (Long-Lived): This is a separate, highly secure token (often just a random string stored in the database, not a JWT) with a long lifespan (e.g., 30 days). The frontend keeps this hidden.

7. The Refresh Workflow

  1. 1. The user logs in. The server sends back an Access Token (15m) and a Refresh Token (30d).
  1. 2. The frontend uses the Access Token to fetch data.
  1. 3. 15 minutes later, the frontend tries to fetch data. The server rejects the Access Token because it expired.
  1. 4. Without bothering the user, the frontend silently sends the Refresh Token to a special /api/refresh endpoint.
  1. 5. The server checks the database. Is the Refresh Token valid? If yes, the server generates a brand new 15-minute Access Token and sends it back.
  1. 6. The frontend resumes fetching data seamlessly. The user never knew this happened!

8. Real-World Decoded JWT

If you decode the middle section (Payload) of a standard JWT, it looks like this:
json
1234567
{
  "sub": "1234567890", // Subject (User ID)
  "name": "John Doe",  // Custom claim
  "role": "admin",     // Custom claim
  "iat": 1516239022,   // Issued At (Unix Timestamp)
  "exp": 1516239922    // Expiration Time (15 mins later)
}

9. Best Practices

  • Use Standard Claims: Stick to standard, registered JWT claim names to keep your tokens lightweight. Use sub (subject) for the user ID, iss for the issuer (your server domain), and aud for audience.

10. Common Mistakes

  • Confusing Encoding with Encryption: Beginners often think a JWT is encrypted because it looks like gibberish (eyJhbGciOi...). It is NOT encrypted; it is just Base64 encoded. You can paste any JWT into a site like jwt.io and instantly read the payload. Never put passwords or sensitive PII (Personally Identifiable Information) inside a JWT.

11. Exercises

  1. 1. Explain the mechanism by which a backend server detects if a user has maliciously altered the payload of their JWT to elevate their privileges to "admin".

12. Coding Challenges

  • Challenge: Visit https://jwt.io/. Look at the Debugger tool. Notice how the token on the left changes instantly if you modify the JSON Payload on the right? Scroll down to the "Verify Signature" section and change the "your-256-bit-secret" field. Watch how changing the secret radically alters the Signature at the end of the token.

13. MCQs with Answers

Question 1

What are the three distinct sections that comprise a standard JSON Web Token (JWT), separated by periods?

Question 2

What is the primary security rationale for utilizing a dual-token architecture consisting of both an Access Token and a Refresh Token?

14. Interview Questions

  • Q: Explain the mathematical relationship between the Header, the Payload, and the Signature of a JWT. Why is it impossible for an attacker to forge a valid signature even if they know the exact hashing algorithm used?
  • Q: A security audit reveals that your development team is storing user passwords directly inside the JWT payload to avoid database lookups. Explain to the team why this is a catastrophic vulnerability.

15. FAQs

Q: Can I manually revoke or ban a specific JWT before it expires? A: Since JWTs are stateless, the server doesn't check the DB on every request, so it doesn't know you banned the user. To manually revoke a JWT, you must implement a "Token Blocklist" in a fast cache like Redis, checking every incoming token against the blocklist. This adds statefulness back into your app, defeating the primary benefit of JWTs. This is why keeping the expiration time short (15 mins) is the preferred solution.

16. Summary

In Chapter 7, we demystified the JSON Web Token (JWT). We broke down its tripartite structure: the Header detailing the algorithm, the Base64 encoded Payload holding the user claims, and the cryptographic Signature ensuring data integrity. We emphasized that JWTs are signed, not encrypted, and must never hold sensitive data. Finally, we explored the critical industry standard of pairing short-lived Access Tokens with long-lived Refresh Tokens to balance absolute security with seamless user experience.

17. Next Chapter Recommendation

We know the theory of JWTs inside and out. It is time to write the code. Proceed to Chapter 8: Implementing JWT Authentication.

Finish this Chapter

Save your progress on your learning path and prepare for coding interview challenges.

Discussion

Join the discussion

Log in or create a free account to participate.

Sort: ·