or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

algorithm-management.mdindex.mdjwk-operations.mdjwks-client.mdjws-operations.mdjwt-operations.md
tile.json

tessl/pypi-pyjwt

JSON Web Token implementation in Python with support for JWT, JWS, JWK, and JWKS

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
pypipkg:pypi/pyjwt@2.10.x

To install, run

npx @tessl/cli install tessl/pypi-pyjwt@2.10.0

index.mddocs/

PyJWT

A comprehensive Python library for JSON Web Token (JWT) implementation providing secure token-based authentication and authorization. PyJWT supports complete RFC 7519 standard with encoding, decoding, and validation using various cryptographic algorithms including HMAC, RSA, ECDSA, and EdDSA signatures.

Package Information

  • Package Name: PyJWT
  • Language: Python
  • Installation: pip install PyJWT (basic HMAC) or pip install PyJWT[crypto] (full cryptographic support)

Core Imports

import jwt

Common usage imports:

from jwt import encode, decode, PyJWT
from jwt.exceptions import InvalidTokenError, ExpiredSignatureError

Basic Usage

import jwt
from datetime import datetime, timedelta, timezone

# Encode a JWT
payload = {
    'user_id': 123,
    'exp': datetime.now(tz=timezone.utc) + timedelta(hours=1)
}
token = jwt.encode(payload, 'your-secret-key', algorithm='HS256')

# Decode and verify a JWT
try:
    decoded = jwt.decode(token, 'your-secret-key', algorithms=['HS256'])
    print(f"User ID: {decoded['user_id']}")
except jwt.ExpiredSignatureError:
    print("Token has expired")
except jwt.InvalidTokenError:
    print("Invalid token")

Architecture

PyJWT provides a layered architecture for JWT operations:

  • JWT Layer: High-level JWT encoding/decoding with claim validation (PyJWT class)
  • JWS Layer: Lower-level JSON Web Signature operations (PyJWS class)
  • JWK Layer: JSON Web Key handling and cryptographic key abstraction (PyJWK, PyJWKSet)
  • JWKS Client: HTTP client for fetching and caching remote key sets (PyJWKClient)
  • Algorithm Support: Pluggable cryptographic algorithm system with HMAC, RSA, ECDSA, EdDSA

This design enables secure token operations across web frameworks, API services, and microservices with comprehensive claim validation, flexible key management, and extensive algorithm support.

Capabilities

JWT Operations

Core JWT encoding and decoding functionality with automatic claim validation, expiration checking, and signature verification. Supports standard claims (exp, nbf, iat, aud, iss, sub) and custom payloads.

def encode(payload: dict, key: str | bytes, algorithm: str = 'HS256', 
          headers: dict = None, json_encoder = None) -> str: ...
def decode(jwt: str | bytes, key: str | bytes = '', algorithms: list = None,
          options: dict = None, audience: str = None, issuer: str = None,
          leeway: float = 0) -> dict: ...
class PyJWT:
    def __init__(self, options: dict = None): ...
    def encode(self, payload: dict, key, algorithm: str = None, 
              headers: dict = None) -> str: ...
    def decode(self, jwt: str | bytes, key = '', algorithms: list = None,
              options: dict = None) -> dict: ...

JWT Operations

JWS Operations

Lower-level JSON Web Signature operations for signing and verifying arbitrary payloads. Provides direct access to the signature layer without JWT-specific claim validation.

class PyJWS:
    def __init__(self, algorithms: list = None, options: dict = None): ...
    def encode(self, payload: bytes, key, algorithm: str = None,
              headers: dict = None) -> str: ...
    def decode(self, jws: str | bytes, key = '', algorithms: list = None,
              options: dict = None) -> bytes: ...
    def get_unverified_header(self, jwt: str | bytes) -> dict: ...

JWS Operations

JSON Web Keys (JWK)

JSON Web Key handling and cryptographic key abstraction supporting RSA, ECDSA, EdDSA, and symmetric keys. Provides key parsing, validation, and algorithm detection.

class PyJWK:
    def __init__(self, jwk_data: dict, algorithm: str = None): ...
    @staticmethod
    def from_dict(obj: dict, algorithm: str = None) -> 'PyJWK': ...
    @staticmethod  
    def from_json(data: str, algorithm: str = None) -> 'PyJWK': ...
    @property
    def key_type(self) -> str: ...
    @property
    def key_id(self) -> str: ...

class PyJWKSet:
    def __init__(self, keys: list): ...
    @staticmethod
    def from_dict(obj: dict) -> 'PyJWKSet': ...
    @staticmethod
    def from_json(data: str) -> 'PyJWKSet': ...
    def __getitem__(self, kid: str) -> PyJWK: ...

JSON Web Keys

JWKS Client

HTTP client for fetching and caching JSON Web Key Sets from remote endpoints. Supports automatic key refresh, caching strategies, and integration with JWT verification.

class PyJWKClient:
    def __init__(self, uri: str, cache_keys: bool = False, 
                max_cached_keys: int = 16, cache_jwk_set: bool = True,
                lifespan: int = 300, headers: dict = None, 
                timeout: int = 30): ...
    def get_signing_key(self, kid: str) -> PyJWK: ...
    def get_signing_key_from_jwt(self, token: str) -> PyJWK: ...
    def get_jwk_set(self, refresh: bool = False) -> PyJWKSet: ...

JWKS Client

Algorithm Management

Cryptographic algorithm registration and management system supporting custom algorithms and algorithm whitelisting for security.

def register_algorithm(alg_id: str, alg_obj) -> None: ...
def unregister_algorithm(alg_id: str) -> None: ...
def get_algorithm_by_name(alg_name: str): ...
def get_unverified_header(jwt: str | bytes) -> dict: ...

Algorithm Management

Exception Types

class PyJWTError(Exception):
    """Base class for all PyJWT exceptions"""

class InvalidTokenError(PyJWTError):
    """Invalid token format or structure"""

class DecodeError(InvalidTokenError):
    """Token parsing or decoding errors"""

class InvalidSignatureError(DecodeError):
    """Signature verification failed"""

class ExpiredSignatureError(InvalidTokenError):
    """Token has expired (exp claim)"""

class ImmatureSignatureError(InvalidTokenError):
    """Token not yet valid (nbf/iat claims)"""

class InvalidAudienceError(InvalidTokenError):
    """Audience claim validation failed"""

class InvalidIssuerError(InvalidTokenError):
    """Issuer claim validation failed"""

class MissingRequiredClaimError(InvalidTokenError):
    """Required claim missing from token"""

class InvalidSubjectError(InvalidTokenError):
    """Subject claim validation failed"""

class InvalidJTIError(InvalidTokenError):
    """JWT ID claim validation failed"""

class PyJWKError(PyJWTError):
    """JSON Web Key related errors"""

class MissingCryptographyError(PyJWKError):
    """Cryptography library required for asymmetric algorithms"""

class PyJWKClientError(PyJWTError):
    """JWKS client errors"""