Signing and Verifying JWTs with python-jose
Encode and decode JWTs with claims, expiry, and audience validation while protecting routes against tampering.
Why JWTs for Stateless Auth
A JWT (JSON Web Token) is a compact, signed token that carries claims about a user. Once your FastAPI app issues a JWT at login, the client sends it back on every request, and you verify it without touching a session store.
- Stateless — the server doesn't store sessions; the signature proves authenticity.
- Tamper-evident — any change to the payload invalidates the signature.
- Portable — the same token works across services that share the secret or public key.
In this lesson we use python-jose to encode (sign) and decode (verify) tokens with claims, expiry, and audience validation.
Anatomy of a JWT
A JWT has three Base64URL parts joined by dots: header.payload.signature.
- Header — algorithm and token type, e.g.
{"alg": "HS256", "typ": "JWT"}. - Payload — the claims (data) such as
sub,exp,aud. - Signature — keyed hash of header + payload, proving the token wasn't altered.
Standard (registered) claims you'll use most: sub (subject/user id), exp (expiry), iat (issued at), aud (audience), iss (issuer). The payload is only encoded, not encrypted, so never put secrets like passwords inside it.
All lessons in this course
- OAuth2 Password Flow and Token Issuance
- Signing and Verifying JWTs with python-jose
- Refresh Tokens and Token Rotation
- Scope-Based Authorization and Role Guards