JWT Authentication
# 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).
6. Request/Response Examples
You pass a JWT to the API in the exact same way you pass a standard token.Request:
7. HTTP Examples
When the server receives the JWT, it does NOT check the database. Instead:- 1. It takes the Header and Payload from the token.
-
2.
It hashes them again using its own
$secretKey.
- 3. If the newly created hash matches the Signature attached to the token, the token is 100% authentic and hasn't been tampered with!
-
4.
The server then reads the
user_iddirectly 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: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
exptimestamp in the payload. Libraries usually do this automatically.
11. Mini Exercises
-
1.
Go to
jwt.io.
- 2. Scroll down to the "Debugger" section.
- 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
How does a server verify a JWT without querying the database?
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_idfrom 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 (likeuser_id) directly from the token without querying a database. While incredibly fast and scalable, JWTs require careful management of expiration times and secret keys.