Hello! Welcome to the next stage of our course.
In our last lesson, we took an important step towards building secure APIs by learning how to control and filter response data to prevent leaking sensitive information like user passwords. Now, we're going to build on that by tackling the core of API security: authentication.
Today's lesson is conceptual but foundational. We will explore how a server can verify a user's identity and trust subsequent requests from them. You will learn about the industry standard for securing modern APIs: JSON Web Tokens (JWTs). Our goal is to understand the role of JWTs and why their stateless nature makes them perfectly suited for the scalable, high-performance APIs you'll build with FastAPI.
The Challenge: Who Are You?
Imagine a user logs into your application. They provide their username and password once. The server verifies them. But what happens on the next request? And the one after that? HTTP, the protocol of the web, is inherently stateless. Each request is independent, and the server has no memory of previous ones.
So, how does the server "remember" a logged-in user without asking for their password every single time? This is the fundamental problem of authentication in web applications.
Let's start with a quick video that contrasts the two primary solutions to this problem: traditional sessions and modern tokens.
Session vs Token Authentication in 100 Seconds
This short video from Fireship provides a fast-paced but excellent overview of session-based versus token-based authentication. Pay close attention to where the "state" (the user's login information) is stored in each approach.
Watch the entire video (it's less than two minutes). Focus on the differences in the workflow between server-side sessions and token-based authentication.
As the video explains, the two main approaches are:
-
Stateful Authentication (Sessions):
- The user logs in.
- The server creates a unique session ID, stores it in its own database or memory along with the user's data, and sends the session ID back to the client (usually in a cookie).
- On every subsequent request, the client sends this session ID.
- The server uses the ID to look up the user's session data.
- The key idea: The server maintains the "state" of the user's session.
-
Stateless Authentication (Tokens):
- The user logs in.
- The server creates a token—a self-contained, digitally signed piece of data containing the user's identity—and sends it to the client.
- The client stores this token (e.g., in memory or local storage) and includes it in the header of every subsequent request.
- The server verifies the token's signature to confirm its authenticity and reads the user's identity directly from it.
- The key idea: The server does not need to store anything. The authentication "state" is carried within the token itself.
For modern APIs, especially those designed to be scalable or serve mobile/frontend applications, the stateless approach using tokens is the dominant standard. The most popular format for these tokens is the JSON Web Token (JWT).
What is a JSON Web Token (JWT)?
Before we dissect a JWT, it's important to clarify two related but distinct concepts.
- Authentication: Verifying who a user is. (e.g., checking a password).
- Authorization: Determining what an authenticated user is allowed to do. (e.g., checking if a user is an admin).
JWTs are primarily used for the step after initial authentication. Once a user proves who they are, a JWT is issued to them. This token then acts as their credential for all future requests, authorizing them to access protected parts of the API.
To get a complete picture of what a JWT is and how it works, let's watch a more detailed explanation.
What Is JWT and Why Should You Use JWT
This video from Web Dev Simplified gives a fantastic, in-depth breakdown of JWTs. It covers the workflow, the structure of a token, and the critical role of the signature.
Watch the video from the beginning until 10:56. It's broken down into a few key parts: Authorization vs. Authentication (0:00 - 3:13): Compares the session and JWT workflows. JWT Structure (5:28 - 8:07): Explains the three parts of a JWT using the jwt.io tool. The Signature (8:07 - 10:56): Details how the signature is created and why it makes JWTs secure.
The Structure of a JWT
As you saw in the video, a JWT is not just a random string. It's a compact, URL-safe string that consists of three parts separated by dots (.):
Header.Payload.Signature
Let's look at each part.

-
Header (Metadata)
The header is a JSON object that typically consists of two parts: the token type (typ), which isJWT, and the signing algorithm being used (alg), such asHS256(HMAC using SHA-256). This JSON is then Base64Url encoded to form the first part of the JWT.{ "alg": "HS256", "typ": "JWT" } -
Payload (The Claims)
The payload is another JSON object that contains the "claims." Claims are statements about an entity (typically, the user) and additional data. This is where you put the information needed to identify the user, like their ID. There are standard, registered claims (likeissfor issuer,expfor expiration time, andsubfor subject), and you can also include your own custom claims.{ "sub": "1234567890", "name": "John Doe", "iat": 1516239022, "exp": 1516242622 }Important: The payload is also Base64Url encoded. This is an encoding, not an encryption. Anyone can decode it and read its contents. Therefore, you must never store sensitive information in the JWT payload.
-
Signature (The Verification)
This is the most critical part for security. To create the signature, you take the encoded header, the encoded payload, a secret key (known only to the server), and sign them with the algorithm specified in the header.Signature = HASH_ALGORITHM( base64UrlEncode(header) + "." + base64UrlEncode(payload), secret )When the server receives a JWT from a client, it performs the same signature calculation using its secret key. If the newly calculated signature matches the signature on the token, the server knows two things:
- The token was issued by this server (because only it knows the secret).
- The payload has not been tampered with since it was issued.
If the signatures do not match, the token is invalid and is rejected.
Why JWTs are Ideal for Stateless APIs
Now we can connect all the pieces and answer the main question: why is this stateless approach so powerful for modern APIs?
What is JWT? Understand JSON Web Tokens
This article from SuperTokens provides a clear, concise summary of the benefits of using JWTs. It directly addresses why they are a good fit for scalable, modern applications.
Read the sections titled "✅ Advantages" and "Benefits of Using JWT Tokens". They reinforce the key advantages of this approach.
The core advantages of JWTs stem from their stateless nature:
-
Scalability: Imagine your API becomes very popular and you need to run it on multiple servers behind a load balancer.
- With stateful sessions, you would need a shared session store (like a Redis database) that all your servers can access. This adds complexity and a potential single point of failure.
- With stateless JWTs, any server instance can validate a token as long as it has the secret key. You can add or remove servers effortlessly without worrying about synchronizing session state.
-
Decoupling and Microservices: Your goal is to serve AI models via an API. You might have one service for user authentication, another for handling predictions, and a third for managing user data. A client can authenticate with the auth service, receive a JWT, and then use that same token to make authenticated requests to all other microservices. As long as each service shares the secret key (or a public key for verification), they can independently validate the user's identity.
-
Cross-Domain and Mobile Friendly: Because the token is sent in a standard
Authorizationheader, it works seamlessly with single-page web applications (built with frameworks like React or Vue) and mobile apps, which might be running on completely different domains from your API.

Conclusion
In this lesson, you've learned the fundamental theory behind modern API authentication. You now understand the "what" and "why" of JSON Web Tokens.
Key Takeaways:
- Stateless vs. Stateful: JWTs enable stateless authentication, where the server does not need to store session information. The state is carried by the client within the token.
- JWT Structure: A JWT consists of a Header, a Payload (containing claims like user ID and expiration), and a Signature.
- The Signature is Key: The digital signature guarantees that the token is authentic and has not been tampered with, even though it's stored on the client side.
- Scalability: The stateless nature of JWTs makes them perfect for scalable, distributed systems like microservices and load-balanced APIs.
We have laid the theoretical groundwork. In our next lesson, we will put this knowledge into practice. You will implement the first part of our authentication flow: creating a user registration endpoint that securely hashes and stores user credentials, setting the stage for us to issue our first JWT.