Auth & security at scale
OAuth2, JWT, IAM patterns, secrets rotation, and least-privilege service auth.
ACME LetsEncrypt Mock Challenge Server in Python
A minimal HTTP server that serves key authorizations for ACME/Let's Encrypt DNS-01 or HTTP-01 challenges during testing and validation.
from http.server import HTTPServer, BaseHTTPRequestHandler
import json
# In-memory store simulating the ACME challenge token -> key authorization pair
challenge_store = {
"token_example": "token_example.key_authorization"
}
class AcmeChallengeHandler(BaseHTTPRequestHandler):
def do_GET(self):
# Extra…
AES GCM encryption and decryption in Python
Encrypt and decrypt data with AES-256-GCM using the cryptography library, including nonce generation and authenticated roundtrip verification.
import os
from cryptography.hazmat.primitives.ciphers.aead import AESGCM
def aes_gcm_demo():
plaintext = b"confidential message"
key = AESGCM.generate_key(bit_length=256)
aesgcm = AESGCM(key)
nonce = os.urandom(12)
ciphertext = aesgcm.encrypt(nonce, plaintext, None)
decrypted = aesgcm.dec…
ChaCha20-Poly1305 mock in Python
Simulates ChaCha20-Poly1305 AEAD encryption and authentication using SHA-256 as a deterministic keystream and tag generator.
from hashlib import sha256
import struct
def chacha20_block(key, counter, nonce):
"""Mock ChaCha20 block: deterministic pseudo-random keystream from key+counter+nonce."""
state_input = key + struct.pack("<I", counter) + nonce + b"ChaCha20"
return sha256(state_input).digest()[:64] # 64-byte keystream bloc…
ECDH key agreement in Python with cryptography
Simulate ECDH key exchange between Alice and Bob, derive a shared secret, and generate a symmetric key with HKDF using the cryptography library.
from cryptography.hazmat.primitives.asymmetric import ec
from cryptography.hazmat.primitives import serialization, hashes
from cryptography.hazmat.primitives.kdf.hkdf import HKDF
def ecdh_mock():
# Alice generates her key pair
alice_private = ec.generate_private_key(ec.SECP256R1())
alice_public = alice_pr…
How to Create and Verify HMAC SHA256 API Signatures in Python
Generate and verify HMAC-SHA256 signatures for API requests using Python's hmac, hashlib, and base64 modules.
import hmac
import hashlib
import base64
import json
from datetime import datetime, timezone
def create_api_signature(secret_key: str, method: str, path: str, timestamp: str, body: dict = None) -> str:
"""Create HMAC-SHA256 signature for API request."""
payload = {
"method": method.upper(),
"p…
How to Create and Verify an OpenID Connect ID Token in Python
Generate and validate a mock OpenID Connect ID token (JWT) with HS256 signing using only the Python standard library.
import base64
import hashlib
import hmac
import json
import time
from typing import Optional
def b64url_encode(data: bytes) -> str:
return base64.urlsafe_b64encode(data).rstrip(b"=").decode("utf-8")
def b64url_decode(data: str) -> bytes:
padding = "=" * (-len(data) % 4)
return base64.urlsafe_b64decode(…
How to Encode and Decode JWT with HS256 in Python
Implement JWT encoding and decoding using HMAC-SHA256 (HS256) with Python's standard library, including signature verification.
import base64
import hashlib
import hmac
import json
def base64url_encode(data: bytes) -> bytes:
return base64.urlsafe_b64encode(data).rstrip(b"=")
def base64url_decode(data: str) -> bytes:
padding = "=" * (-len(data) % 4)
return base64.urlsafe_b64decode(data + padding)
def encode_jwt(payload: dict, …
How to Hash Passwords and Authenticate Users in Python
A beginner-friendly dataclass-based design that hashes passwords with PBKDF2 and verifies them securely using constant-time comparisons.
import hashlib
import hmac
import secrets
from dataclasses import dataclass
from typing import Optional
@dataclass
class User:
id: int
username: str
password_hash: str
salt: str
def hash_password(password: str) -> tuple[str, str]:
salt = secrets.token_hex(16)
password_hash = hashlib.pbkdf2_…
How to Implement Refresh Token Rotation in Python
A mock auth service that issues, rotates, and validates refresh tokens, revoking old tokens on reuse to prevent replay attacks.
import time
import hashlib
import secrets
from typing import Dict, Optional, Tuple
class MockTokenService:
"""Simulates refresh token rotation for a simple auth system."""
def __init__(self):
# Token hash -> (user_id, rotation_count, expires_at)
self._active_tokens: Dict[str, Tuple[str, int,…
How to Implement a CSRF Token Double Submit Mock in Python
A mock CSRF protection class that generates and validates double-submit tokens using HMAC-SHA256 with a secret key.
import hmac
import hashlib
import secrets
class CSRFProtection:
def __init__(self, secret_key: str):
self.secret_key = secret_key.encode("utf-8")
def generate_token(self) -> str:
random_value = secrets.token_hex(16)
signature = hmac.new(
self.secret_key, random_value.enco…
How to Implement a Vault Dynamic Database Credentials Mock in Python
A Python dataclass-based mock of HashiCorp Vault that issues short-lived database credentials, tracks leases, and revokes them, demonstrating dynamic secrets rotation.
import time
import json
from dataclasses import dataclass, field
from typing import Dict
@dataclass
class DynamicCredential:
username: str
password: str
lease_duration: int
created_at: float = field(default_factory=time.time)
def is_valid(self) -> bool:
return time.time() - self.created_…
How to Mock Certificate Pinning with SPKI Hash in Python
Shows how to compute and compare a certificate's SubjectPublicKeyInfo SHA-256 hash for pinning validation in Python.
import hashlib
import base64
import ssl
import socket
class MockCertificatePinner:
"""Demonstrates SPKI hash pinning for certificate validation."""
def __init__(self, pinned_spki_hashes):
self.pinned_hashes = set(pinned_spki_hashes)
def get_spki_hash(self, cert_pem):
"""Compute t…
How to Mock Environment Variables in Python
A context manager that injects and restores environment variables for isolated testing of config-dependent code.
import os
class EnvInjector:
def __init__(self, mock_vars=None):
self.mock_vars = mock_vars or {}
self.original = {}
def __enter__(self):
for key, value in self.mock_vars.items():
if key in os.environ:
self.original[key] = os.environ[key]
os.env…
How to Mock Environment Variables in Python for 12-Factor Config
Read 12-factor config from env vars and test/mock them with unittest.mock.patch.dict without touching the real environment.
import os
import json
from unittest.mock import patch
def load_config(env_prefix="APP"):
"""Read 12-factor style config from env vars"""
required = ["DATABASE_URL", "API_KEY"]
optional = {"PORT": "8080", "DEBUG": "false"}
config = {}
for key in required:
full_key = f"{env_prefix}_{key…
How to Mock HTTP Responses to Verify HSTS Headers in Python
This code demonstrates how to use unittest.mock to intercept and capture HTTP response headers, specifically the Strict-Transport-Security header, from a mocked HTTPServer handler for security validation.
from http.server import BaseHTTPRequestHandler, HTTPServer
from unittest.mock import patch
class StrictTransportMock(BaseHTTPRequestHandler):
def do_GET(self):
self.send_response(200)
self.send_header("Strict-Transport-Security", "max-age=31536000; includeSubDomains")
self.end_headers()
…
How to Mock KMS Envelope Encryption in Python
Demonstrates a minimal mock of AWS KMS envelope encryption flow with AES-GCM data key wrapping and unwrapping.
import base64
import json
import os
import hashlib
class MockKMS:
"""Minimal mock of AWS KMS envelope encryption flow."""
def generate_data_key(self):
# Simulate KMS returning a plaintext and encrypted data key
plaintext_key = os.urandom(32)
encrypted_key = hashlib.sha256(plaintext_k…
How to Mock OAuth 2.0 Device Code Flow in Python
A mock implementation of the OAuth 2.0 device authorization grant for testing authentication flows without a real provider.
import hashlib
import time
import uuid
class DeviceCodeFlowMock:
def __init__(self):
self.device_codes = {}
def request_device_code(self, client_id, scope="read write"):
device_code = uuid.uuid4().hex
user_code = str(uuid.uuid4().int)[:8].upper()
expires_in = 300
inte…
How to Mock a CORS Allow Origin Whitelist in Python
A decorator-based mock of a CORS middleware that whitelists allowed origins and injects proper Access-Control-Allow-Origin headers while rejecting others.
from functools import wraps
class MockCORSConfig:
def __init__(self, allowed_origins):
self.allowed_origins = allowed_origins
def is_origin_allowed(self, origin):
return origin in self.allowed_origins
def cors_middleware(config):
def decorator(handler):
@wraps(handler)
…
How to Mock a Redis Session Store in Python
An in-memory RedisSessionStore class with TTL-based expiry, get/set/delete/exists methods, and JSON field support—perfect for testing and prototyping without a live Redis.
import time
import json
from collections import defaultdict
class RedisSessionStore:
"""In-memory mock of a Redis-backed session store."""
def __init__(self, ttl=3600):
self._data = defaultdict(dict)
self._expires = {}
self._ttl = ttl
def set(self, session_id, field, value):
…
How to Mock an mTLS Client Certificate in Python
Create a self-signed client certificate and key with OpenSSL, load them into an SSL context, and simulate an mTLS handshake in Python for testing.
import ssl
import socket
import subprocess
import tempfile
from pathlib import Path
def create_mock_certificates():
"""Generate self-signed client certificate and key for mTLS testing."""
with tempfile.TemporaryDirectory() as tmpdir:
cert_path = Path(tmpdir) / "client.crt"
key_path = Path(tmpd…
How to Sign and Verify with Ed25519 in Python
A minimal Ed25519 sign-and-verify helper that generates a key pair, signs a message, and checks the signature with the cryptography library.
import hashlib
from cryptography.hazmat.primitives.asymmetric import ed25519
from cryptography.hazmat.primitives import serialization
def sign_verify_mock(
message: bytes,
private_key: ed25519.Ed25519PrivateKey,
public_key: ed25519.Ed25519PublicKey
) -> tuple[bool, bytes]:
signature = private_key.sign…
How to Test X-Content-Type-Options nosniff in Python with Mocks
Mock httpx responses and verify that a server's X-Content-Type-Options header includes nosniff to prevent MIME sniffing.
import httpx
from unittest.mock import Mock, patch
def fetch_headers(url: str) -> dict:
response = httpx.get(url)
return dict(response.headers)
def mock_nosniff_check(response) -> bool:
content_type = response.headers.get("content-type", "")
x_content_type_options = response.headers.get("x-content-ty…
How to Tune scrypt Parameters in Python
Adjust scrypt work factor (N) to hit a target hashing time with a mock benchmark loop, then return tunable parameters and a derived key.
import hashlib
def tune_scrypt_params(target_time=0.1, base_n=2**14, base_r=8, base_p=1):
"""Mock tuning of scrypt params based on target time."""
n, r, p = base_n, base_r, base_p
iterations = 0
for _ in range(5): # simple mock adjustment loop
iterations += 1
mock_time = 0.05 + (…
How to implement OCSP stapling mock in Python
Simulate OCSP stapling with a caching mechanism that mocks certificate status lookups for TLS handshake validation.
import hashlib
import time
class OCSPStapler:
def __init__(self, cert_serial: str, issuer_hash: str):
self.cert_serial = cert_serial
self.issuer_hash = issuer_hash
self.cache = {}
def _mock_query_ocsp(self, serial: str) -> dict:
"""Simulate OCSP responder lookup."""
di…
Browse by section
Each section groups closely related Python snippets.
Auth & security at scale — Python code examples
What you will find here
This page collects auth & security at scale snippets — short, copy-ready Python you can paste into our free online IDE and run without installing anything. Each sample includes a plain-English explanation and the full source code.
Samples vs tutorials and challenges
Samples are quick reference — one concept per page. For step-by-step teaching, use our Python tutorials. To test yourself, try quizzes or coding challenges. Clean up style with the Python formatter.