JSON Web Token (JWT) Library

1.4.0 · active · verified Thu Apr 09

This is a JSON Web Token (JWT) library for Python 3, developed by GehirnInc, providing functionalities to encode and decode JWTs. It leverages the `cryptography` library for handling cryptographic operations, including key loading, signing, and verification. Version 1.4.0 is the latest stable release. It has a steady release cadence, focusing on stability and security rather than rapid feature development.

Warnings

Install

Imports

Quickstart

This example demonstrates how to encode and decode a JWT using an RSA key pair. It generates an in-memory key pair for illustration. Key elements include specifying the algorithm, handling `datetime` objects in the payload with `datetime_format`, and explicitly listing allowed algorithms and audience during decoding for security.

import jwt
import datetime
from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.primitives.asymmetric import rsa
from cryptography.hazmat.backends import default_backend

# --- Generate a key pair for demonstration (in a real app, load from secure storage) ---
private_key = rsa.generate_private_key(
    public_exponent=65537,
    key_size=2048,
    backend=default_backend()
)
public_key = private_key.public_key()

# --- Encode a JWT ---
payload = {
    "user_id": 123,
    "username": "testuser",
    "exp": datetime.datetime.now(datetime.timezone.utc) + datetime.timedelta(minutes=30),
    "aud": "my-service-audience"
}
algorithm = "RS256"

# For a real application, private_key would be loaded from a secure source.
encoded_jwt = jwt.encode(
    payload,
    private_key,
    algorithm=algorithm,
    headers={"kid": "my_key_id"},
    datetime_format="datetime" # Use "datetime" for `datetime` objects in payload
)
print("Encoded JWT:", encoded_jwt)

# --- Decode a JWT ---
# For a real application, public_key would be loaded from a secure source.
try:
    decoded_jwt = jwt.decode(
        encoded_jwt,
        public_key,
        algorithms=[algorithm], # REQUIRED: Must specify allowed algorithms
        audience="my-service-audience", # RECOMMENDED: Validate audience
        datetime_format="datetime"
    )
    print("\nDecoded JWT:", decoded_jwt)
except jwt.exceptions.JWTDecodeError as e:
    print(f"\nError decoding JWT: {e}")
except Exception as e:
    print(f"\nAn unexpected error occurred: {e}")

view raw JSON →