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…
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…
Enforce TLS 1.2 Minimum in Python
Create an SSL context with a minimum TLS version of 1.2 to enforce secure connections.
import ssl
def get_min_tls_version():
context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
context.minimum_version = ssl.TLSVersion.TLSv1_2
return context.minimum_version
if __name__ == "__main__":
min_version = get_min_tls_version()
print(f"Minimum TLS version set to: {min_version.name} (value: {mi…
Fetch Secrets from a Mock Secrets Manager in Python
Build a minimal in-memory secrets manager that stores and retrieves secret values, raising a KeyError for missing names.
import json
class SecretsManager:
"""Mock secrets manager that returns secrets from a local store."""
def __init__(self, store=None):
self.store = store or {
"api_key": "mock-api-key-123",
"db_password": "s3cret-p@ss",
"jwt_secret": "dev-only-secret"
}
…
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 Revoke Tokens with a Blacklist Set in Python
A minimal TokenBlacklist class using a Python set to revoke, batch-revoke, check, and remove expired tokens for simple token invalidation.
import time
class TokenBlacklist:
def __init__(self):
self.blacklisted_tokens = set()
def revoke(self, token):
self.blacklisted_tokens.add(token)
print(f"Token {token} revoked. Blacklist size: {len(self.blacklisted_tokens)}")
def revoke_batch(self, tokens):
before = len(s…
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…
OAuth2 authorization code flow mock in Python
A minimal HTTP server that mocks the OAuth2 authorization code flow, issuing codes via /authorize and exchanging them for tokens at /token.
import json
from http.server import BaseHTTPRequestHandler, HTTPServer
from urllib.parse import urlparse, parse_qs
AUTH_CODE_STORE = {}
CLIENT_ID = "demo-client"
REDIRECT_URI = "http://localhost:8000/callback"
class OAuthHandler(BaseHTTPRequestHandler):
def do_GET(self):
parsed = urlparse(self.path)
…
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.