FastAPI - Beginner to Pro / Authentication & Authorization

JSON Web Token (JWT) Overview

πŸ” JSON Web Tokens (JWT)

In this lesson, we are going to break down JWT, which stands for JSON Web Token.

JWT is one of the most widely used authorization mechanisms in modern APIs β€” especially in backend systems and microservice architectures.


πŸ“Œ What is a JSON Web Token?

A JSON Web Token (JWT) is a self-contained way to securely transmit information between two or more parties using a JSON object.

It is:

  • Digitally signed

  • Compact

  • URL-safe

  • Stateless

Because it is digitally signed, the server can verify whether the token has been altered after being issued.


πŸ”Ž Important Clarification: Authentication vs Authorization

JWT is not authentication.

JWT is an authorization mechanism.

  • πŸ”‘ Authentication β†’ Verifies who you are (login with username/password).

  • πŸ›‚ Authorization β†’ Verifies what you are allowed to access.

Typical flow:

  1. User logs in (authentication).

  2. Server validates credentials.

  3. Server returns a JWT.

  4. Client sends JWT with every request.

  5. Server validates the token before allowing access.

This avoids logging in on every request.


🧱 JSON Web Token Structure

Every JWT has three parts, separated by dots:

HEADER.PAYLOAD.SIGNATURE

Visually:

Each part is Base64 encoded and joined using dots.


🧩 The JWT Header

The header contains metadata about the token.

It usually includes:

  • alg β†’ Signing algorithm (e.g., RS256)

  • typ β†’ Token type (e.g., JWT)

Example

{
  "alg": "RS256",
  "typ": "JWT"
}

This JSON object is Base64-encoded to form the first part of the JWT.


πŸ“¦ The JWT Payload

The payload contains the actual data. The data inside a payload is called claims.

Example

{
  "sub": "123",
  "email": "user@example.com",
  "role": "admin",
  "exp": 1710000000
}

🏷️ What Are Claims?

Claims are key-value pairs inside the payload.

There are 3 types of claims:

1️⃣ Registered Claims

Predefined standard claims recommended by JWT specification.

Common ones:

Claim

Meaning

sub

Subject (usually user ID)

exp

Expiration time

iat

Issued at

nbf

Not before

iss

Issuer

aud

Audience

Example:

{
  "sub":"42",
  "exp":1710000000,
  "iat":1709990000
}

βœ… Used for security & token validation

βœ… Standard across systems

2️⃣ Public Claims

Custom claims defined by you but intended to be public.

Example:

{
  "role":"admin",
  "username":"bhaskar"
}

⚠️ To avoid collision, use unique names (sometimes namespaced like app_role).

Used for:

  • Roles

  • Permissions

  • Application-level data

3️⃣ Private Claims

Custom claims shared only between specific parties.

Example:

{
  "department_id":"IT-09",
  "internal_flag":true
}

These are:

  • Not standardized

  • Agreed upon between backend & frontend

Used for internal system logic.

🚨 Important Security Notes

βœ” JWT payload is readable (just Base64 encoded)

βœ” Do NOT store passwords or sensitive secrets

βœ” Always set exp claim

βœ” Keep payload minimal


πŸ” The JWT Signature

The signature ensures the token hasn’t been altered.

It is created by: For HMAC (HS256) algorithm:

HMACSHA256(
  base64UrlEncode(header) + "." +
  base64UrlEncode(payload),
  secret
)

The secret key:

  • Lives on the server

  • Is never shared with the client

If the client discovers the secret key, they can forge valid tokens β€” which is a massive security risk.


πŸ”Ž What Happens if the Token is Modified?

You can try test encoding and decoding tokens at:

<https://jwt.io>

If:

  • Header changes

  • Payload changes

  • Secret changes

The signature becomes invalid.

The server will reject the request immediately.

That’s why JWT is trusted for authorization.

On that site, if you modify even a single character of the secret, you’ll instantly see:

Invalid Signature

This proves how sensitive and secure the mechanism is.


πŸ“Œ How JWT is Sent in Requests

Most APIs send JWTs in the Authorization header using the Bearer schema:

Authorization: Bearer <your_token_here>

πŸš€ Practical Use Case: Multiple Applications (SSO Concept)

Imagine a company owns:

  • App 1 β†’ Cryptocurrency trading platform

  • App 2 β†’ Digital wallet

Instead of logging in twice:

  • User logs in once.

  • Both apps share the same secret.

  • Both servers can decode the same JWT.

  • Seamless experience for the user.

Visually:

This pattern is common in:

  • Microservices architectures

  • Distributed systems

  • Stateless APIs

  • Enterprise applications

Each service can decode the JWT, extract user information, and authorize requests without implementing login again.