python-jose: JOSE Implementation for Python

3.5.0 · active · verified Sat Mar 28

python-jose is an active Python library implementing the JSON Object Signing and Encryption (JOSE) standards, including JSON Web Signature (JWS), JSON Web Encryption (JWE), JSON Web Key (JWK), JSON Web Algorithms (JWA), and JSON Web Tokens (JWT). Currently at version 3.5.0, it maintains a regular release schedule with significant updates to Python version support and cryptographic backends.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates encoding and decoding a JSON Web Token (JWT) using a symmetric (HS256) algorithm. For asymmetric algorithms (like RS256), you would use public/private key pairs instead of a shared secret. Ensure `JWT_SECRET_KEY` is set securely in your environment for production use.

import os
from jose import jwt

# IMPORTANT: Use a strong, securely generated secret key in production
SECRET_KEY = os.environ.get('JWT_SECRET_KEY', 'your-super-secret-key-please-change-me')
ALGORITHM = "HS256"

# 1. Encode a JWT
payload = {"user_id": "123", "username": "testuser", "role": "admin"}
encoded_jwt = jwt.encode(payload, SECRET_KEY, algorithm=ALGORITHM)
print(f"Encoded JWT: {encoded_jwt}")

# 2. Decode and verify a JWT
try:
    decoded_payload = jwt.decode(encoded_jwt, SECRET_KEY, algorithms=[ALGORITHM])
    print(f"Decoded Payload: {decoded_payload}")
except Exception as e:
    print(f"Error decoding JWT: {e}")

view raw JSON →