Skip to main content

Core JWT authentication and authorization logic for Axioms packages

Project description

Axioms Core

Core JWT authentication and authorization logic shared by Axioms packages for FastAPI, Django, and Flask.

Overview

axioms-core-py provides framework-agnostic JWT token validation, JWKS key retrieval with background refresh, and claim-based authorization. This package is used by:

  • axioms-fastapi - FastAPI integration
  • axioms-drf-py - Django REST Framework integration
  • axioms-flask-py - Flask integration

Features

  • Framework-agnostic JWT validation - Works with any Python web framework
  • Async JWKS fetching with background refresh - Non-blocking JWKS retrieval using httpx with periodic background updates
  • Thread-safe caching - In-memory JWKS cache with configurable TTL
  • Secure by default - Only allows asymmetric algorithms (RS256, ES256, PS256, etc.)
  • Configurable - Support for custom claim names for scopes, roles, and permissions
  • Production-ready - Comprehensive error handling and logging

Installation

pip install axioms-core-py

Quick Start

Initialize JWKS Manager (Recommended)

Initialize the JWKS manager at application startup to enable background refresh:

from axioms_core import initialize_jwks_manager, shutdown_jwks_manager

# At startup
config = {
    "AXIOMS_JWKS_URL": "https://auth.example.com/.well-known/jwks.json",
    "AXIOMS_AUDIENCE": "your-api-audience",
}

initialize_jwks_manager(
    config=config,
    refresh_interval=1800,  # Refresh every 30 minutes
    cache_ttl=600,          # Cache for 10 minutes
    prefetch=True           # Fetch JWKS immediately
)

# At shutdown
shutdown_jwks_manager()

Token Validation

from axioms_core import get_key_from_jwks_json, check_token_validity
import jwt

# Get token header
header = jwt.get_unverified_header(token)
kid = header.get("kid")
alg = header.get("alg")

# Get public key from JWKS (uses cache)
key = get_key_from_jwks_json(kid, config)

# Validate token
payload = check_token_validity(
    token=token,
    key=key,
    alg=alg,
    audience="your-api-audience",
    issuer="https://auth.example.com"
)

if payload:
    print(f"Token valid for user: {payload.sub}")
else:
    print("Token validation failed")

Authorization Checks

from axioms_core import check_scopes, check_roles, check_permissions

# Check scopes (space-separated string)
has_scope = check_scopes("read:data write:data", ["read:data"])

# Check roles (list)
has_role = check_roles(["admin", "editor"], ["admin"])

# Check permissions (list)
has_permission = check_permissions(["users:read", "users:write"], ["users:read"])

Configuration

The core package uses a generic configuration system that works with dicts or objects:

# Dictionary config
config = {
    "AXIOMS_JWKS_URL": "https://auth.example.com/.well-known/jwks.json",
    "AXIOMS_ISS_URL": "https://auth.example.com",
    "AXIOMS_AUDIENCE": "your-api-audience",
    "AXIOMS_DOMAIN": "auth.example.com",  # Alternative to AXIOMS_ISS_URL
}

# Or object config (e.g., from pydantic-settings, django.conf.settings)
class Config:
    AXIOMS_JWKS_URL = "https://auth.example.com/.well-known/jwks.json"
    AXIOMS_AUDIENCE = "your-api-audience"

Configuration Hierarchy

The package follows this hierarchy for JWKS URL:

  1. AXIOMS_JWKS_URL (if set, used directly)
  2. AXIOMS_ISS_URL + /.well-known/jwks.json
  3. https://{AXIOMS_DOMAIN} + /.well-known/jwks.json

JWKS Manager

The JWKS manager provides:

  • Background refresh: Periodically fetches JWKS to stay up-to-date with key rotations
  • Caching: Reduces latency and load on the authorization server
  • Thread-safety: Safe to use in multi-threaded environments
  • Lazy initialization: Works without explicit initialization (falls back to on-demand fetch)

Configuration Options

initialize_jwks_manager(
    jwks_url=None,           # JWKS URL (derived from config if None)
    refresh_interval=3600,   # Refresh every hour (seconds)
    cache_ttl=600,           # Cache TTL: 10 minutes (seconds)
    config=None,             # Configuration dict/object
    prefetch=True            # Pre-fetch JWKS before starting background thread
)

Allowed Algorithms

Only secure asymmetric algorithms are allowed to prevent algorithm confusion attacks:

  • RS256, RS384, RS512 (RSA with SHA)
  • ES256, ES384, ES512 (ECDSA with SHA)
  • PS256, PS384, PS512 (RSA-PSS with SHA)

Error Handling

The package raises AxiomsError for authentication/authorization failures:

from axioms_core.helper import AxiomsError

try:
    payload = check_token_validity(...)
except AxiomsError as e:
    print(f"Error: {e.error}")
    print(f"Status: {e.status_code}")

Development

# Install dev dependencies
pip install -e ".[dev]"

# Run tests
pytest

# Format code
black src tests

# Lint
ruff check src tests

License

MIT License - see LICENSE file for details.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

axioms_core_py-0.0.2rc11763933648.tar.gz (33.7 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

axioms_core_py-0.0.2rc11763933648-py3-none-any.whl (17.9 kB view details)

Uploaded Python 3

File details

Details for the file axioms_core_py-0.0.2rc11763933648.tar.gz.

File metadata

File hashes

Hashes for axioms_core_py-0.0.2rc11763933648.tar.gz
Algorithm Hash digest
SHA256 fba0c0faf2e1ed16a3cd9ab381584f008cfc278efa3707367b6662cd9c96ca1b
MD5 f5df39acf69d8efac97eaf98a36f608d
BLAKE2b-256 388665a3679e814bc756e6a92c2d806c36efe36e7ebf8e277cf120c231ff6ad4

See more details on using hashes here.

Provenance

The following attestation bundles were made for axioms_core_py-0.0.2rc11763933648.tar.gz:

Publisher: release.yml on abhishektiwari/axioms-core-py

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file axioms_core_py-0.0.2rc11763933648-py3-none-any.whl.

File metadata

File hashes

Hashes for axioms_core_py-0.0.2rc11763933648-py3-none-any.whl
Algorithm Hash digest
SHA256 163bf293aff5a8576f97716ff27a2e44c1a7db75ce442950853676d60dff2b0e
MD5 0f8e2892571f57c643c5d21d9560cc92
BLAKE2b-256 7620f82cb4210b7e767d4dd10465cdd160ee33a879a30a514aebc7ba44295538

See more details on using hashes here.

Provenance

The following attestation bundles were made for axioms_core_py-0.0.2rc11763933648-py3-none-any.whl:

Publisher: release.yml on abhishektiwari/axioms-core-py

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page