Auth & security at scale
OAuth2, JWT, IAM patterns, secrets rotation, and least-privilege service auth.
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 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 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 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 mock DNS CAA record lookups in Python
Parse and filter DNS CAA records with a mock lookup function, demonstrating how certificate authorities validate domain authorization.
import dnslib
def parse_caa_record(record_string):
"""Parse a DNS CAA record string into its components."""
parts = record_string.split()
flags = int(parts[0])
tag = parts[1]
value = parts[2]
return flags, tag, value
def mock_caa_lookup(domain, caa_records):
"""Mock DNS CAA lookup that re…
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.