Typing Stubs for python-jose
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
- gotcha Attempting to import or run code directly from `types-python-jose` will result in `ImportError` or `AttributeError`.
- gotcha This stub package requires the `python-jose` runtime library to be installed and present for your application to actually function.
- deprecated The `python-jose` library itself has been noted as 'barely maintained' by some sources as of early 2024, suggesting `PyJWT` or `joserfc` as potentially more secure and actively maintained alternatives for JWT operations.
- breaking While typeshed aims for minimal breaking changes, any version bump of `types-python-jose` can introduce changes that might cause your code to fail type checking, especially if the underlying `python-jose` library or typing standards evolve.
Install
-
pip install types-python-jose -
pip install python-jose[cryptography] types-python-jose
Imports
- jwt
from jose import jwt
- JWS
from jose import jws
Quickstart
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}")