Skip to main content
RESTful Principles
CHAPTER 15 Beginner

JWT Authentication

Updated: May 13, 2026
5 min read

# CHAPTER 15

JWT Authentication

1. Introduction

In the last chapter, we stored tokens in the database. But what if you have 10 million users and millions of requests per second? Hitting the database just to check if a token is valid becomes a massive bottleneck. Enter JWT (JSON Web Tokens). In Chapter 15, we will explore this revolutionary standard that allows servers to verify a user's identity using cryptography *without* ever touching the database.

2. Learning Objectives

By the end of this chapter, you will be able to:
  • Explain what a JSON Web Token (JWT) is.
  • Understand the three parts of a JWT: Header, Payload, and Signature.
  • Explain how JWTs allow for database-less authentication.
  • Understand the security concepts behind signing tokens.
  • Identify the pros and cons of JWTs vs Database Tokens.

3. Beginner-Friendly Explanation

Imagine a traditional database token as a coat check ticket. You hand the server your ticket, the server looks through the coatroom (database), finds the coat matching the ticket, and says "Ah, this is John's coat."

A JWT is like an official Passport. The passport contains all your information right there on the paper (Name, Age, ID). Crucially, the passport has an unforgeable cryptographic stamp (Signature) from the government. When you show it to the bouncer, they just look at the stamp. If the stamp is real, they trust the information on the passport immediately. They don't need to call the government database to verify it.

4. Real-World Examples

  • Microservices: A massive company like Netflix has hundreds of different backend servers. Instead of every server checking the main database, they pass a JWT around. Any server can read the JWT and instantly know who the user is.
  • Single Sign-On (SSO): When you log into an app using "Sign in with Google," Google often issues a JWT that contains your profile data, which the app can instantly verify.

5. Detailed Code Examples

A JWT is a long string separated by two periods into three parts: Header.Payload.Signature Example: eyJhbGciOiJIUzI1Ni... . eyJ1c2VyX2lkIjo1... . SflKxwRJSMeKKF...

Here is a conceptual look at how a JWT is created in PHP (Note: In reality, you should use a library like firebase/php-jwt).

php
12345678910111213141516171819202122232425
<?php
// 1. HEADER (Tells the algorithm used)
$header = json_encode([&#039;typ' => 'JWT', 'alg' => 'HS256']);

// 2. PAYLOAD (The actual data we want to store inside the token)
$payload = json_encode([
    &#039;user_id' => 123,
    &#039;role' => 'admin',
    &#039;exp' => time() + 3600 // Expires in 1 hour
]);

// Base64Url encode them (makes them safe for URLs/Headers)
$base64UrlHeader = str_replace([&#039;+', '/', '='], ['-', '_', ''], base64_encode($header));
$base64UrlPayload = str_replace([&#039;+', '/', '='], ['-', '_', ''], base64_encode($payload));

// 3. SIGNATURE (The cryptographic stamp)
// We hash the header and payload using a SECRET KEY that only the server knows
$secretKey = &#039;my_super_secret_server_key';
$signature = hash_hmac(&#039;sha256', $base64UrlHeader . "." . $base64UrlPayload, $secretKey, true);
$base64UrlSignature = str_replace([&#039;+', '/', '='], ['-', '_', ''], base64_encode($signature));

// The final JWT!
$jwt = $base64UrlHeader . "." . $base64UrlPayload . "." . $base64UrlSignature;
echo $jwt;
?>

6. Request/Response Examples

You pass a JWT to the API in the exact same way you pass a standard token.

Request:

http
123
GET /orders HTTP/1.1
Host: api.store.com
Authorization: Bearer eyJhbGciOiJIUzI1Ni...

7. HTTP Examples

When the server receives the JWT, it does NOT check the database. Instead:
  1. 1. It takes the Header and Payload from the token.
  1. 2. It hashes them again using its own $secretKey.
  1. 3. If the newly created hash matches the Signature attached to the token, the token is 100% authentic and hasn't been tampered with!
  1. 4. The server then reads the user_id directly from the payload.

8. JSON Examples

If you decode the Payload section of a JWT (which anyone can do, it is NOT encrypted), it looks like this:
json
1234567
{
  "iss": "https://api.myapp.com",
  "iat": 1698765432,
  "exp": 1698769032,
  "user_id": 5,
  "email": "user@example.com"
}

9. Best Practices

  • DO NOT put sensitive data in the payload: JWT payloads are merely encoded, *not encrypted*. Anyone who intercepts the token (or even the user themselves) can decode the payload and read it. Never put passwords or credit cards in a JWT payload.
  • Use short expiration times (exp): Because JWTs are not checked against a database, you cannot easily "revoke" them. If a hacker steals a JWT, it remains valid until it expires. Therefore, JWTs should expire quickly (e.g., 15 minutes to 1 hour).
  • Keep the Secret Key safe: If a hacker discovers your $secretKey, they can forge valid JWTs and log in as anyone, including administrators.

10. Common Mistakes

  • Trying to build JWT from scratch: Cryptography is hard. Never write your own JWT generation/validation code in production. Always use an established library via Composer (e.g., composer require firebase/php-jwt).
  • Ignoring the Expiration Check: Always verify that the current time is less than the exp timestamp in the payload. Libraries usually do this automatically.

11. Mini Exercises

  1. 1. Go to jwt.io.
  1. 2. Scroll down to the "Debugger" section.
  1. 3. Change the data in the "PAYLOAD" box (e.g., change the name). Notice how the "SIGNATURE" string at the bottom changes entirely. This is how the server knows if someone tampered with the data!

12. Coding Challenges

Challenge 1: If a JWT payload contains "exp": 1700000000, write a PHP if statement to check if the token is expired using the time() function.

13. MCQs with Answers

Question 1

How does a server verify a JWT without querying the database?

Q2. Is the data inside a JWT payload hidden from the client? A) Yes, it is heavily encrypted. B) No, it is just Base64 encoded. Anyone can decode and read it. *Answer: B*
Question 3

What is the biggest disadvantage of a standard JWT compared to a database token?

14. Interview Questions

  • Q: Explain the three parts of a JSON Web Token.
  • Q: How does JWT validation improve API performance in a microservice architecture?
  • Q: Since anyone can decode a JWT payload, how do we know a hacker didn't change the user_id from 5 to 1 (Admin) before sending it to the server?

15. FAQs

Q: If JWTs can't be revoked, what happens when a user logs out? A: This is the hardest part of JWTs. Usually, "logging out" just means the client deletes the token from its local storage. Technically, the token is still valid on the server until it expires. For strict security, servers maintain a "blacklist" of revoked JWTs in a fast cache like Redis, but this somewhat defeats the "database-less" benefit of JWTs!

16. Summary

In Chapter 15, we explored JSON Web Tokens (JWT). We learned that JWTs contain three parts (Header, Payload, Signature) and allow servers to verify identities cryptographically. Because the server trusts the signature, it can read data (like user_id) directly from the token without querying a database. While incredibly fast and scalable, JWTs require careful management of expiration times and secret keys.

17. Next Chapter Recommendation

We mentioned that JWTs should have short lifespans. But if a token expires every 15 minutes, the user would have to log in constantly! How do we solve this? Proceed to Chapter 16: OAuth 2.0 Basics to learn about Access Tokens, Refresh Tokens, and modern authorization flows.

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: ·