PyJWT is a Python library for encoding and decoding JSON Web Tokens. It provides a simple interface for issuing signed tokens and validating their signatures and claims. section 8.2 section 8.3
Use PyJWT to:
- Create a payload containing claims such as issuer, subject, audience, issue time, and expiration. section 8.2
- Issue an HS256 token with a shared signing key or a PS256 token with a private key. section 8.2
- Validate tokens by restricting algorithms and checking the expected audience and issuer; expired tokens are also rejected. section 8.3
Issuing and validating an API token
Build a payload with an issuer, user subject, API audience, current UTC issue time, and one-hour expiration. Call jwt.encode(payload=payload, key="password", algorithm="HS256") to issue the token. Later, call jwt.decode(jwt=token, key="password", algorithms=["HS256"], audience="https://apithreats.com/api", issuer="https://auth.apithreats.com") to recover the payload. A successful call returns claims; an invalid token raises an exception. section 8.2 section 8.3
Listing 8.3 Example JWT payload
# file: ch08/jwt_generator_pyjwt_hs256.py
from datetime import datetime, timezone, timedelta
now = datetime.now(timezone.utc)
payload = {
"iss": "https://auth.apithreats.com",
"sub": "23456543",
"aud": "https://apithreats.com/api",
"iat": now,
"exp": (now + timedelta(hours=1))
}
Inspect a complete payload example showing issuer, subject, audience, issue time, and expiration before signing it with PyJWT. section 8.2
