PyJWT

2.12.1 · active · verified Sat Mar 28

PyJWT is the canonical Python implementation of JSON Web Tokens (RFC 7519), supporting HMAC (HS256/384/512), RSA (RS256/384/512, PS256/384/512), EC (ES256/384/512), and OKP (EdDSA) algorithms. Current stable version is 2.12.1 (released March 2026). The project follows an irregular release cadence driven by security advisories and feature PRs, with several releases per year. Asymmetric algorithms (RS*, ES*, PS*, EdDSA) require the optional `cryptography` extra.

Warnings

Install

Imports

Quickstart

Encode and decode a signed JWT with HS256, validating exp/aud/iss claims. token is a str in PyJWT 2.x.

import os
import jwt
from datetime import datetime, timezone, timedelta

SECRET = os.environ.get('JWT_SECRET', 'change-me-use-32-plus-chars-prod!')

# Encode
payload = {
    "sub": "user-123",
    "iss": "my-service",
    "aud": "my-api",
    "exp": datetime.now(tz=timezone.utc) + timedelta(hours=1),
    "iat": datetime.now(tz=timezone.utc),
}
token: str = jwt.encode(payload, SECRET, algorithm="HS256")
print("token type:", type(token))  # <class 'str'> in 2.x

# Decode — always pass algorithms= to prevent alg confusion attacks
try:
    decoded = jwt.decode(
        token,
        SECRET,
        algorithms=["HS256"],       # required; never omit
        audience="my-api",          # validates 'aud' claim
        issuer="my-service",        # validates 'iss' claim
        options={"require": ["exp", "iat", "sub"]},
    )
    print(decoded)
except jwt.ExpiredSignatureError:
    print("token expired")
except jwt.InvalidTokenError as e:
    print("invalid token:", e)

view raw JSON →