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…
Build a Mock OIDC Userinfo Endpoint in Python with Flask
Create a local mock OIDC userinfo endpoint in Flask that returns a standard JSON user payload, ideal for testing auth flows without a real identity provider.
from flask import Flask, jsonify
app = Flask(__name__)
@app.route("/userinfo")
def userinfo():
mock_user = {
"sub": "1234567890",
"name": "John Doe",
"email": "john@example.com",
"email_verified": True,
"groups": ["admin", "dev"]
}
return jsonify(mock_user)
if __n…
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…
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 Check Negotiated Cipher Suite in Python
Connect to a TLS server with Python's ssl module and print the negotiated protocol version and cipher suite details.
import ssl
import socket
def get_cipher_suites(hostname, port=443):
context = ssl.create_default_context()
context.set_ciphers("DEFAULT:@SECLEVEL=2")
with socket.create_connection((hostname, port), timeout=5) as sock:
with context.wrap_socket(sock, server_hostname=hostname) as ssock:
…
How to Create Secure Session Cookies in Python with Secure, HttpOnly, and SameSite Flags
This code demonstrates how to create a secure session cookie using Python's stdlib, setting Secure, HttpOnly, and SameSite attributes to protect against common web vulnerabilities.
import http.cookies
import secrets
class SessionManager:
def __init__(self):
self.cookie = http.cookies.SimpleCookie()
def create_session_cookie(self, session_id=None):
session_id = session_id or secrets.token_hex(16)
self.cookie["session"] = session_id
self.cookie["session"][…
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 Enforce a Strict Referrer Policy in Python
Validate HTTP headers to enforce a strict same-origin Referrer policy, accepting only origin-only URLs or absent Referer values.
import re
from unittest.mock import patch
def strict_referrer_policy(headers):
"""Return True if Referer header is absent or strictly same-origin."""
referer = headers.get("Referer")
if referer is None:
return True
# Strict-Origin-When-Cross-Origin allows same-origin full URL
# but here we…
How to Generate PKCE Code Challenge in Python
This Python script generates a PKCE code verifier and its corresponding S256 code challenge for secure OAuth2 authorization flows.
import base64
import hashlib
import os
import secrets
import string
def generate_code_verifier(length=64):
alphabet = string.ascii_letters + string.digits + "-._~"
return "".join(secrets.choice(alphabet) for _ in range(length))
def generate_code_challenge(code_verifier, method="S256"):
if method == "S256…
How to Generate and Verify HMAC Signatures in Python
Create and validate HMAC-SHA256 signatures with a shared secret key using Python's hmac and hashlib modules.
import hashlib
import hmac
SECRET_KEY = b"pepper-secret-2024"
def generate_hmac(message: str) -> str:
return hmac.new(SECRET_KEY, message.encode("utf-8"), hashlib.sha256).hexdigest()
def verify_hmac(message: str, received_hmac: str) -> bool:
expected = generate_hmac(message)
return hmac.compare_digest(e…
How to Hash Passwords Securely in Python
Hash passwords with PBKDF2, random salts, and constant pepper, plus generate secure API keys using Python's stdlib.
import hashlib
import secrets
import time
import hmac
def hash_password(password: str, salt: str = None, pepper: str = "static-pepper") -> dict:
"""Hash a password with a random salt and constant pepper."""
if salt is None:
salt = secrets.token_hex(16)
salted = f"{pepper}{salt}{password}"
dig…
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 Hash Passwords with bcrypt in Python
Hash a plaintext password with bcrypt using a randomly generated salt, then verify a plaintext attempt against the stored hash.
import bcrypt
def hash_password(password: str) -> str:
"""Hash a password using bcrypt with a generated salt."""
salt = bcrypt.gensalt()
return bcrypt.hashpw(password.encode("utf-8"), salt).decode("utf-8")
def check_password(password: str, hashed: str) -> bool:
"""Verify a plaintext password against …
How to Hash and Verify Passwords in Python
Hash passwords securely with PBKDF2-SHA256 and verify them using a constant-time comparison.
import hashlib
import hmac
import secrets
from typing import Tuple
def hash_password(password: str, salt: str = None) -> Tuple[str, str]:
"""Hash a password with a random salt using PBKDF2-SHA256."""
salt = salt or secrets.token_hex(16)
hashed = hashlib.pbkdf2_hmac(
"sha256", password.encode("utf…
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 Implement an HSTS Preload List Mock in Python
Implements a mock HSTS preload list in Python that supports adding, removing, checking domains with subdomain inheritance, and listing domains.
import json
class HSTSPreloadList:
def __init__(self):
self.domains = {}
def add_domain(self, domain, include_subdomains=False, max_age=31536000):
self.domains[domain] = {
"include_subdomains": include_subdomains,
"max_age": max_age
}
def remove_domain(sel…
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…
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.