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:
import jwt # the PyJWT libraryfrom datetime import datetime, timedelta, timezone# Issue a token at logintoken = jwt.encode({"user_id": 42, "exp": datetime.now(timezone.utc) + timedelta(hours=1)},"SECRET_KEY", algorithm="HS256")# Verify it on a later requestclaims = jwt.decode(token, "SECRET_KEY", algorithms=["HS256"])claims["user_id"] # 42 — raises if signature invalid or expired
Security essentials
Key takeaways
- 01A JWT is a signed, self-contained token of claims (header.payload.signature).
- 02The server verifies the signature — no server-side session storage needed.
- 03Keep the signing secret out of code and set an expiry (exp).
- 04A JWT is signed, not encrypted — never put secrets in the payload.
- 05Common for stateless API authentication.
