Reference library

Auth & security at scale

OAuth2, JWT, IAM patterns, secrets rotation, and least-privilege service auth.

41 matches
Auth & security at scale easy

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.

flask oidc userinfo
Python
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…
13 0 Open
Auth & security at scale medium

ChaCha20-Poly1305 mock in Python

Simulates ChaCha20-Poly1305 AEAD encryption and authentication using SHA-256 as a deterministic keystream and tag generator.

crypto aead mock
Python
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…
14 0 Open
Auth & security at scale medium

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.

ecdh cryptography key-agreement
Python
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…
15 0 Open
Auth & security at scale easy

Enforce TLS 1.2 Minimum in Python

Create an SSL context with a minimum TLS version of 1.2 to enforce secure connections.

tls ssl security
Python
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…
13 0 Open
Auth & security at scale easy

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.

secrets-management security mock
Python
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"
        }
…
16 0 Open
Auth & security at scale easy

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.

cookies session security
Python
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"][…
14 0 Open
Auth & security at scale medium

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.

hmac sha256 authentication
Python
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…
14 0 Open
Auth & security at scale medium

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.

jwt oidc security
Python
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(…
14 0 Open
Auth & security at scale medium

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.

jwt hmac authentication
Python
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, …
16 0 Open
Auth & security at scale easy

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.

referrer security headers
Python
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…
15 0 Open
Auth & security at scale easy

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.

pkce oauth2 security
Python
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…
15 0 Open
Auth & security at scale easy

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.

hmac security cryptography
Python
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…
15 0 Open
Auth & security at scale easy

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.

password hashing security
Python
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…
15 0 Open
Auth & security at scale medium

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.

security password hashing pbkdf2
Python
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_…
16 0 Open
Auth & security at scale easy

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.

bcrypt password security
Python
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 …
13 0 Open
Auth & security at scale easy

How to Hash and Verify Passwords in Python

Hash passwords securely with PBKDF2-SHA256 and verify them using a constant-time comparison.

password-hashing security pbkdf2
Python
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…
14 0 Open
Auth & security at scale medium

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.

auth oauth refresh-token
Python
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,…
11 0 Open
Auth & security at scale medium

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.

csrf security hmac
Python
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…
13 0 Open
Auth & security at scale medium

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.

vault secrets database
Python
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_…
16 0 Open
Auth & security at scale easy

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.

hsts security domains
Python
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…
15 0 Open
Auth & security at scale medium

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.

certificate ssl pinning
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…
14 0 Open
Auth & security at scale medium

How to Mock Environment Variables in Python

A context manager that injects and restores environment variables for isolated testing of config-dependent code.

env vars context manager testing
Python
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…
14 0 Open
Auth & security at scale medium

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.

environment-variables 12-factor testing
Python
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…
13 0 Open
Auth & security at scale medium

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.

hsts mock security
Python
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()
  …
13 0 Open

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.