Typing Stubs for python-jose

3.5.0.20260408 · active · verified Sat Apr 11

This package provides PEP 561 type stubs for the `python-jose` library, enabling static type checking tools like Mypy and Pyright to analyze code that uses `python-jose`. It allows developers to benefit from type hints for JOSE (JSON Object Signing and Encryption) operations, including JWS, JWE, JWK, and JWT. The current version is 3.5.0.20260408, with releases tied to the typeshed project's daily automated updates.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates basic JWT (JSON Web Token) encoding and decoding using the `python-jose` library. Installing `types-python-jose` alongside it provides static type checking benefits for these operations. It shows how to encode a payload into a JWT using a symmetric key and then decode it. Remember to manage your `SECRET_KEY` securely in a production environment, ensuring it meets the length requirements for your chosen algorithm (e.g., at least 32 bytes for HS256). The `python-jose` library supports various JOSE specifications including JWS, JWE, and JWK, with different cryptographic backends.

import os
from jose import jwt
from jose.constants import ALGORITHMS

# In a real application, load a secret from environment variables
# or a secure configuration management system.
SECRET_KEY = os.environ.get('JOSE_SECRET_KEY', 'your-secret-key-that-is-at-least-32-bytes-long')

# Encoding a JWT
payload = {
    "sub": "user123",
    "name": "John Doe",
    "admin": True
}

# Use a strong algorithm like HS256 for symmetric keys
# For asymmetric keys (RS256, ES256), you'd use public/private key pairs.
algorithm = ALGORITHMS.HS256

# Ensure your secret is bytes for HS algorithms
if isinstance(SECRET_KEY, str):
    # Pad secret if too short for HS256 (requires 32 bytes for 256-bit key)
    SECRET_KEY_BYTES = SECRET_KEY.encode('utf-8').ljust(32, b'\0')[:32]
else:
    SECRET_KEY_BYTES = SECRET_KEY

encoded_jwt = jwt.encode(payload, SECRET_KEY_BYTES, algorithm=algorithm)
print(f"Encoded JWT: {encoded_jwt}")

# Decoding a JWT
try:
    decoded_payload = jwt.decode(encoded_jwt, SECRET_KEY_BYTES, algorithms=[algorithm])
    print(f"Decoded payload: {decoded_payload}")
except jwt.JWTError as e:
    print(f"JWT decoding error: {e}")

# Example with an incorrect key (for demonstration of type safety and error handling)
try:
    wrong_key = b"wrong-secret".ljust(32, b'\0')[:32] # Pad for demonstration
    jwt.decode(encoded_jwt, wrong_key, algorithms=[algorithm])
except jwt.JWTError as e:
    print(f"Expected error with wrong key: {e}")

view raw JSON →