Reference library

Auth & security at scale

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

5 matches
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 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 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 a CORS Allow Origin Whitelist in Python

A decorator-based mock of a CORS middleware that whitelists allowed origins and injects proper Access-Control-Allow-Origin headers while rejecting others.

cors security middleware
Python
from functools import wraps


class MockCORSConfig:
    def __init__(self, allowed_origins):
        self.allowed_origins = allowed_origins

    def is_origin_allowed(self, origin):
        return origin in self.allowed_origins


def cors_middleware(config):
    def decorator(handler):
        @wraps(handler)
        …
16 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

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.