Reference library

Auth & security at scale

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

31 matches
Auth & security at scale medium

How to mock Argon2 password hashing in Python

This code demonstrates a mock Argon2 password hasher using HMAC-SHA256 iterations, providing hash and verify methods that mimic Argon2's salted, iterated derivation.

password-hashing security argon2
Python
import hashlib
import hmac
import os


class Argon2Mock:
    def __init__(self, salt_size=16, hash_len=32):
        self.salt_size = salt_size
        self.hash_len = hash_len
        
    def hash(self, password: str, salt: bytes = None) -> str:
        if salt is None:
            salt = os.urandom(self.salt_size)
 …
14 0 Open
Auth & security at scale medium

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.

dns security caa
Python
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…
18 0 Open
Auth & security at scale medium

How to redact secrets from log messages in Python

This code defines a logging.Filter subclass that automatically redacts sensitive keys like password, token, and API key from any dict logged.

logging security redaction
Python
import logging
from dataclasses import dataclass


@dataclass
class ApiResponse:
    status: int
    body: dict


class SecretRedactor(logging.Filter):
    SENSITIVE_KEYS = {"password", "token", "secret", "api_key"}

    def filter(self, record: logging.LogRecord) -> bool:
        if isinstance(record.msg, dict):
    …
12 0 Open
Auth & security at scale medium

How to sign and verify JWT RS256 in Python

Generate RSA keys, create a JWT signed with RS256, verify its signature, and decode the payload using the cryptography library.

jwt rs256 rsa
Python
import json
import time
import base64
import hmac
import hashlib
from cryptography.hazmat.primitives.asymmetric import rsa
from cryptography.hazmat.primitives import serialization, hashes
from cryptography.hazmat.primitives.asymmetric import padding
from cryptography.hazmat.primitives.asymmetric.utils import encode_ds…
13 0 Open
Auth & security at scale medium

Implement RSA OAEP Padding in Python

Implements OAEP-style padding with MGF1 using SHA-256 from the Python standard library for RSA encryption prep.

rsa oaep cryptography
Python
import os
import hashlib


def mgf1(seed, length, hash_func=hashlib.sha256):
    """MGF1 mask generation function."""
    output = b""
    counter = 0
    while len(output) < length:
        c = counter.to_bytes(4, "big")
        output += hash_func(seed + c).digest()
        counter += 1
    return output[:length]


…
12 0 Open
Auth & security at scale medium

Mock client credentials machine auth in Python

This code simulates the OAuth2 client-credentials flow for service-to-service calls, generating a mock bearer token with expiry and caching, plus a revoke method, using only the standard library.

oauth2 auth mock
Python
import time
import hashlib
import secrets

class MachineAuth:
    """Mock client-credentials machine auth for service-to-service calls."""
    
    def __init__(self, client_id, client_secret):
        self.client_id = client_id
        self.client_secret = client_secret
        self._token = None
        self._expire…
15 0 Open
Auth & security at scale medium

OAuth2 authorization code flow mock in Python

A minimal HTTP server that mocks the OAuth2 authorization code flow, issuing codes via /authorize and exchanging them for tokens at /token.

oauth2 http-server mock-server
Python
import json
from http.server import BaseHTTPRequestHandler, HTTPServer
from urllib.parse import urlparse, parse_qs

AUTH_CODE_STORE = {}
CLIENT_ID = "demo-client"
REDIRECT_URI = "http://localhost:8000/callback"

class OAuthHandler(BaseHTTPRequestHandler):
    def do_GET(self):
        parsed = urlparse(self.path)
    …
14 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.