Reference library

Auth & security at scale

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

8 matches
Auth & security at scale medium

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.

acme letsencrypt http-server
Python
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…
16 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
Auth & security at scale medium

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.

oauth2 device-flow mock
Python
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…
13 0 Open
Auth & security at scale medium

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.

redis session mock
Python
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):
   …
12 0 Open
Auth & security at scale medium

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.

mtls ssl certificates
Python
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…
14 0 Open
Auth & security at scale medium

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.

security httpx mocking
Python
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…
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.