← Back to all products
$9
API Auth Middleware
Multi-strategy API authentication for bearer tokens, API keys, and HMAC request signatures.
JSONMarkdownPython
📄 Product Preview
Try the interactive reader and demo tools below, or get the full product with all content unlocked.
📖 Interactive Reader (Free Preview) ⚙ Try Demo Tools 📦 Download Free Sample📁 File Structure 9 files
api-auth-middleware/
├── LICENSE
├── README.md
├── examples/
│ └── config.example.json
├── free-sample.zip
├── guide/
│ ├── 01_api-auth-middleware.md
│ ├── 02_features.md
│ └── 03_quick-start.md
├── index.html
└── src/
└── main.py
📖 Documentation Preview README excerpt
API Auth Middleware
Multi-strategy API authentication middleware for bearer tokens, API keys, and HMAC request signatures. Zero dependencies.
Part of the Auth Vault toolkit by [CodeVault](https://codevault.dev).
Features
- Three auth strategies: Bearer token, API key, HMAC-SHA256 signature
- Middleware chaining: combine strategies per route
- Per-route configuration: different auth for different endpoints
- HMAC-SHA256 request signing with replay protection (timestamp + nonce)
- Timing-safe comparison on all credential checks
- RFC 7807 Problem Details error responses
- CLI tool for key management, request signing, and demo server
- Zero dependencies — Python stdlib only
Quick Start
# Generate a new API key
python3 src/main.py generate --name "My App" --scopes read write
# List registered API keys
python3 src/main.py list
# Validate an API key
python3 src/main.py validate --key "av_abc123..."
# Sign a request with HMAC
python3 src/main.py sign --client demo-client --secret s3cret \
--method GET --path /api/data
# Start demo server with protected routes
python3 src/main.py serve --port 8000
Using as a Library
from main import AuthMiddleware
middleware = AuthMiddleware()
# Configure routes
middleware.add_route("/api/public", strategies=[], allow_anonymous=True)
middleware.add_route("/api/data", strategies=["bearer", "api_key"],
required_scopes=["read"])
middleware.add_route("/api/admin", strategies=["hmac"],
required_scopes=["admin"])
# Register credentials
middleware.bearer.add_token("my-token", "user123", ["read", "write"])
plaintext, key = middleware.key_store.generate_key("My App", ["read"])
middleware.hmac_validator.add_client("client1", "shared-secret")
# Authenticate a request
result, error = middleware.authenticate(
method="GET", path="/api/data",
headers={"Authorization": "Bearer my-token"},
*... continues with setup instructions, usage examples, and more.*
📄 Code Sample .py preview
src/main.py
#!/usr/bin/env python3
"""
API Auth Middleware — Bearer Tokens, API Keys & HMAC Signatures
================================================================
Multi-strategy API authentication middleware supporting bearer token
validation, API key lookup, and HMAC request signature verification.
Includes middleware chaining, per-route auth configuration, and
structured JSON error responses (RFC 7807 Problem Details).
Why build your own middleware? Because most auth middleware packages
are tied to Flask, Django, or FastAPI. This implementation works with
any WSGI-compatible server or even raw HTTP handlers, and you can
read every line of the auth logic.
Zero dependencies. Import or run as CLI.
Part of the Auth Vault toolkit by DataNest.
License: MIT
"""
from __future__ import annotations
import base64
import hashlib
import hmac
import json
import logging
import os
import secrets
import threading
import time
import urllib.parse
from dataclasses import dataclass, field, asdict
from datetime import datetime, timezone
from http.server import HTTPServer, BaseHTTPRequestHandler
from pathlib import Path
from typing import Any, Callable
# ---------------------------------------------------------------------------
# Logging
# ---------------------------------------------------------------------------
logger = logging.getLogger("api_auth_middleware")
# ---------------------------------------------------------------------------
# Constants
# ---------------------------------------------------------------------------
# Where we persist API keys (JSON file)
DEFAULT_STORAGE_PATH = Path("api_keys.json")
# ... 773 more lines ...