Skip to main content
Albero Academy

JWT Authentication

Stateless auth with signed JSON Web Tokens.

APIs9 min

A JWT (JSON Web Token) is a signed, self-contained token that carries claims — like a user id and roles. The server issues it at login and verifies its signature on later requests, so it doesn't need to store server-side sessions. This makes it popular for stateless APIs.

What's in a token

A JWT has three parts (header.payload.signature). The payload holds the claims; the signature proves it wasn't tampered with:

encode & verify
import jwt # the PyJWT library
from datetime import datetime, timedelta, timezone
# Issue a token at login
token = jwt.encode(
{"user_id": 42, "exp": datetime.now(timezone.utc) + timedelta(hours=1)},
"SECRET_KEY", algorithm="HS256")
# Verify it on a later request
claims = jwt.decode(token, "SECRET_KEY", algorithms=["HS256"])
claims["user_id"] # 42 — raises if signature invalid or expired

Security essentials

Key takeaways

  1. 01A JWT is a signed, self-contained token of claims (header.payload.signature).
  2. 02The server verifies the signature — no server-side session storage needed.
  3. 03Keep the signing secret out of code and set an expiry (exp).
  4. 04A JWT is signed, not encrypted — never put secrets in the payload.
  5. 05Common for stateless API authentication.

Finished this chapter?

Mark it complete to track your progress through Python.