CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-authlib

The ultimate Python library in building OAuth and OpenID Connect servers and clients.

Pending

Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

Overview
Eval results
Files

jose.mddocs/

JOSE Implementation

Complete implementation of JSON Object Signing and Encryption (JOSE) standards including JWT (RFC 7519), JWS (RFC 7515), JWE (RFC 7516), and JWK (RFC 7517). Provides both high-level JWT operations and low-level JOSE primitives with support for all standard algorithms.

Capabilities

JSON Web Token (JWT)

High-level JWT operations for creating and validating JSON Web Tokens with automatic header handling and claims validation.

class JsonWebToken:
    """High-level JWT implementation with automatic algorithm detection."""
    
    def __init__(self, algorithms: list = None, private_headers: set = None) -> None:
        """
        Initialize JWT processor.
        
        Args:
            algorithms: List of allowed algorithms
            private_headers: Set of private header names
        """

    def encode(self, header: dict, payload: dict, key, check: bool = True) -> str:
        """
        Encode a JWT token.
        
        Args:
            header: JWT header dictionary containing 'alg' and optional parameters
            payload: JWT payload/claims dictionary
            key: Signing key (string, RSA key, EC key, etc.)
            check: Whether to validate header parameters
            
        Returns:
            JWT token string
        """

    def decode(self, data: str, key, claims_cls=None, claims_options: dict = None, claims_params: dict = None) -> dict:
        """
        Decode and validate a JWT token.
        
        Args:
            data: JWT token string
            key: Verification key
            claims_cls: Claims validation class
            claims_options: Claims validation options
            claims_params: Additional claims parameters
            
        Returns:
            Decoded payload dictionary
        """

# Pre-configured JWT instance with registered algorithms
jwt: JsonWebToken

JSON Web Signature (JWS)

Low-level JWS operations for signing and verifying arbitrary payloads with full control over headers and serialization formats.

class JsonWebSignature:
    """Low-level JWS implementation for signing arbitrary data."""
    
    def __init__(self, algorithms: list = None, private_headers: set = None) -> None:
        """
        Initialize JWS processor.
        
        Args:
            algorithms: List of allowed algorithms
            private_headers: Set of private header names
        """

    def serialize_compact(self, protected: dict, payload: bytes, key) -> str:
        """
        Create a JWS compact serialization.
        
        Args:
            protected: Protected header dictionary
            payload: Raw payload bytes
            key: Signing key
            
        Returns:
            JWS compact serialization string
        """

    def deserialize_compact(self, data: str, key, sender_key=None) -> dict:
        """
        Deserialize and verify a JWS compact serialization.
        
        Args:
            data: JWS compact serialization string
            key: Verification key
            sender_key: Optional sender key for verification
            
        Returns:
            Dictionary with 'header' and 'payload' keys
        """

    def serialize_json(self, payload: bytes, signatures: list) -> str:
        """
        Create a JWS JSON serialization.
        
        Args:
            payload: Raw payload bytes
            signatures: List of signature configurations
            
        Returns:
            JWS JSON serialization string
        """

class JWSAlgorithm:
    """Base class for JWS algorithms."""
    
    name: str
    description: str
    
    def prepare_key(self, raw_data) -> Key:
        """Prepare and validate the signing key."""
    
    def sign(self, bytestr: bytes, key: Key) -> bytes:
        """Sign the given bytes with the key."""
    
    def verify(self, bytestr: bytes, signature: bytes, key: Key) -> bool:
        """Verify the signature against the bytes and key."""

JSON Web Encryption (JWE)

JWE implementation for encrypting payloads with support for key encryption algorithms and content encryption algorithms.

class JsonWebEncryption:
    """JWE implementation for encrypting JSON data."""
    
    def __init__(self, algorithms: list = None, private_headers: set = None) -> None:
        """
        Initialize JWE processor.
        
        Args:
            algorithms: List of allowed algorithms
            private_headers: Set of private header names
        """

    def serialize_compact(self, protected: dict, plaintext: bytes, recipient_key, sender_key=None) -> str:
        """
        Create a JWE compact serialization.
        
        Args:
            protected: Protected header dictionary
            plaintext: Raw plaintext bytes
            recipient_key: Recipient's public key
            sender_key: Optional sender's private key
            
        Returns:
            JWE compact serialization string
        """

    def deserialize_compact(self, data: str, private_key, sender_key=None) -> dict:
        """
        Deserialize and decrypt a JWE compact serialization.
        
        Args:
            data: JWE compact serialization string
            private_key: Recipient's private key
            sender_key: Optional sender's public key
            
        Returns:
            Dictionary with 'header' and 'payload' keys
        """

class JWEAlgorithm:
    """Base class for JWE key encryption algorithms."""
    
    name: str
    description: str
    
    def prepare_key(self, raw_data) -> Key:
        """Prepare the key for encryption/decryption."""
    
    def wrap(self, cek: bytes, key: Key, header: dict) -> tuple:
        """Wrap the Content Encryption Key."""
    
    def unwrap(self, ek: bytes, key: Key, header: dict) -> bytes:
        """Unwrap the encrypted key to get CEK."""

class JWEEncAlgorithm:
    """Base class for JWE content encryption algorithms."""
    
    name: str
    description: str
    
    def encrypt(self, plaintext: bytes, aad: bytes, iv: bytes, key: bytes) -> tuple:
        """Encrypt plaintext with additional authenticated data."""
    
    def decrypt(self, ciphertext: bytes, aad: bytes, iv: bytes, tag: bytes, key: bytes) -> bytes:
        """Decrypt ciphertext and verify authentication tag."""

JSON Web Key (JWK)

JWK implementation for representing cryptographic keys in JSON format with support for key operations and key sets.

class JsonWebKey:
    """JWK implementation for key management."""
    
    def __init__(self, algorithms: list = None) -> None:
        """
        Initialize JWK processor.
        
        Args:
            algorithms: List of supported algorithms
        """

    def import_key(self, raw_data, params: dict = None) -> Key:
        """
        Import a key from various formats.
        
        Args:
            raw_data: Key data (PEM, DER, JWK dict, etc.)
            params: Additional key parameters
            
        Returns:
            Key instance
        """

    def export_key(self, key: Key) -> str:
        """
        Export a key to JWK format.
        
        Args:
            key: Key instance to export
            
        Returns:
            JWK JSON string
        """

    def import_key_set(self, data: dict) -> KeySet:
        """
        Import a JWK Set.
        
        Args:
            data: JWK Set dictionary
            
        Returns:
            KeySet instance
        """

class Key:
    """Base class for cryptographic keys."""
    
    kty: str  # Key type
    use: str  # Key use
    alg: str  # Algorithm
    kid: str  # Key ID
    
    def as_dict(self) -> dict:
        """Export key as dictionary."""
    
    def as_json(self) -> str:
        """Export key as JSON string."""
    
    def as_pem(self) -> bytes:
        """Export key as PEM format."""

class KeySet:
    """Container for multiple keys."""
    
    def __init__(self, keys: list = None) -> None:
        """Initialize key set with optional keys list."""
    
    def add_key(self, key: Key) -> None:
        """Add a key to the set."""
    
    def find_by_kid(self, kid: str) -> Key:
        """Find key by key ID."""
    
    def as_dict(self) -> dict:
        """Export key set as dictionary."""

Key Types

Specific key implementations for different cryptographic algorithms.

class RSAKey(Key):
    """RSA key implementation."""
    
    def __init__(self, key_data: dict = None) -> None:
        """Initialize RSA key from key data dictionary."""
    
    @classmethod
    def generate_key(cls, key_size: int = 2048, auto_kid: bool = False) -> 'RSAKey':
        """Generate a new RSA key pair."""

class ECKey(Key):
    """Elliptic Curve key implementation."""
    
    def __init__(self, key_data: dict = None) -> None:
        """Initialize EC key from key data dictionary."""
    
    @classmethod
    def generate_key(cls, crv: str = 'P-256', auto_kid: bool = False) -> 'ECKey':
        """Generate a new EC key pair."""

class OKPKey(Key):
    """Octet Key Pair for EdDSA."""
    
    def __init__(self, key_data: dict = None) -> None:
        """Initialize OKP key from key data dictionary."""
    
    @classmethod
    def generate_key(cls, crv: str = 'Ed25519', auto_kid: bool = False) -> 'OKPKey':
        """Generate a new OKP key pair."""

class OctKey(Key):
    """Symmetric key implementation."""
    
    def __init__(self, key_data: dict = None) -> None:
        """Initialize symmetric key from key data dictionary."""
    
    @classmethod
    def generate_key(cls, key_size: int = 256, auto_kid: bool = False) -> 'OctKey':
        """Generate a new symmetric key."""

Claims Validation

JWT claims validation with support for standard and custom claims.

class BaseClaims:
    """Base class for claims validation."""
    
    def __init__(self, payload: dict, header: dict = None) -> None:
        """
        Initialize claims validator.
        
        Args:
            payload: JWT payload dictionary
            header: Optional JWT header dictionary
        """
    
    def validate(self, now: int = None) -> None:
        """
        Validate all claims.
        
        Args:
            now: Current timestamp for time-based validations
        """

class JWTClaims(BaseClaims):
    """Standard JWT claims validation."""
    
    def validate_iss(self) -> None:
        """Validate issuer claim."""
    
    def validate_sub(self) -> None:
        """Validate subject claim."""
    
    def validate_aud(self) -> None:
        """Validate audience claim."""
    
    def validate_exp(self, now: int = None, leeway: int = 0) -> None:
        """Validate expiration time claim."""
    
    def validate_nbf(self, now: int = None, leeway: int = 0) -> None:
        """Validate not before claim."""
    
    def validate_iat(self, now: int = None, leeway: int = 0) -> None:
        """Validate issued at claim."""

Algorithm Registration

Functions to register standard and custom algorithms.

def register_jws_rfc7518(cls: type) -> None:
    """
    Register RFC 7518 JWS algorithms.
    
    Args:
        cls: JWS class to register algorithms on
    """

def register_jwe_rfc7518(cls: type) -> None:
    """
    Register RFC 7518 JWE algorithms.
    
    Args:
        cls: JWE class to register algorithms on
    """

def register_jws_rfc8037(cls: type) -> None:
    """
    Register RFC 8037 EdDSA algorithms.
    
    Args:
        cls: JWS class to register algorithms on
    """

Error Handling

JOSE-specific error classes for different failure scenarios.

class JoseError(AuthlibBaseError):
    """Base JOSE error."""

class DecodeError(JoseError):
    """Error decoding JOSE data."""

class MissingAlgorithmError(JoseError):
    """Algorithm not found or not supported."""

class UnsupportedAlgorithmError(JoseError):
    """Algorithm is not supported."""

class BadSignatureError(JoseError):
    """Invalid signature detected."""

class InvalidHeaderParameterNameError(JoseError):
    """Invalid header parameter name."""

class InvalidClaimError(JoseError):
    """Invalid claim value."""

class MissingClaimError(JoseError):
    """Required claim is missing."""

class InsecureClaimError(JoseError):
    """Claim contains insecure data."""

class ExpiredTokenError(JoseError):
    """Token has expired."""

class InvalidTokenError(JoseError):
    """Token is invalid."""

Usage Examples

Basic JWT Operations

from authlib.jose import JsonWebToken, jwt

# Simple JWT with HMAC
token = jwt.encode({'alg': 'HS256'}, {'user': 'alice'}, 'secret')
payload = jwt.decode(token, 'secret')

# JWT with RSA key
from authlib.jose import RSAKey

rsa_key = RSAKey.generate_key(2048)
token = jwt.encode({'alg': 'RS256'}, {'user': 'alice'}, rsa_key)
payload = jwt.decode(token, rsa_key)

JWS with Custom Payload

from authlib.jose import JsonWebSignature

jws = JsonWebSignature()
header = {'alg': 'HS256'}
payload = b'custom data'

# Sign
token = jws.serialize_compact(header, payload, 'secret')

# Verify
data = jws.deserialize_compact(token, 'secret')
original_payload = data['payload']

JWE Encryption

from authlib.jose import JsonWebEncryption, RSAKey

jwe = JsonWebEncryption()
recipient_key = RSAKey.generate_key(2048)

# Encrypt
header = {'alg': 'RSA-OAEP', 'enc': 'A256GCM'}
token = jwe.serialize_compact(header, b'secret data', recipient_key)

# Decrypt
data = jwe.deserialize_compact(token, recipient_key)
plaintext = data['payload']

Install with Tessl CLI

npx tessl i tessl/pypi-authlib

docs

common-utilities.md

django-integration.md

flask-integration.md

http-clients.md

index.md

jose.md

oauth1.md

oauth2.md

oidc.md

tile.json