Part I · The request
Chapter 5: Security by default
The promiseDjango handles security for you.
The machineryHow CSRF tokens, cryptographic signing with fallback keys, CSP headers, and host checks work inside the middleware stack — and the exact edges where defaults stop protecting you.
Read any introduction to Django and you will meet the same reassurance within a page: Django handles CSRF, XSS, clickjacking, host-header poisoning, and cryptographic signing out of the box. Spin up a project with "startproject", turn on MIDDLEWARE, and the framework quietly stands guard between the open internet and your views.
That reputation is earned, and it is also half-dangerous. Django has no single security firewall watching every packet. Instead, its defenses are five ordinary middleware layers and three utility primitives scattered across the request pipeline, each enforcing one narrow invariant — and each cheap enough that turning all four HTTP security middlewares on together adds less than a tenth of a millisecond to a request.
What four security shields actually cost
ch05-bench. Turning on all four HTTP security middlewares adds +37.8 us on a GET request and +85.6 us on a full double-submit POST check. Notice that Django 6’s ContentSecurityPolicyMiddleware adds only +6.0 us when a view ignores its nonce, because LazyNonce never touches the operating system’s CSPRNG until a template actually asks for it.Those timings destroy the old excuse for stripping security middleware out of hot endpoints: +37.8 us on GET and +85.6 us on POST is noise next to a single database query or template render. What does break in production is rarely performance — it is misunderstanding where each check lives and what triggers it.
Five gates, not one wall
Follow a hostile HTTP request from the WSGI or ASGI socket into the newsroom app and notice how much depends on exact ordering and exact wiring.
HttpRequest validates "Host" against ALLOWED_HOSTS, yet nothing calls it until either SecurityMiddleware builds a redirect URL or CommonMiddleware trips it unconditionally as a side effect. Behind a TLS-terminating proxy, forgetting SECURE_PROXY_SSL_HEADER turns SECURE_SSL_REDIRECT into an infinite 301 loop, while misconfiguring the proxy lets any client spoof HTTPS.
Once past transport checks, CsrfViewMiddleware runs during process_view — after URL resolution has found the view callable and inspected csrf_exempt — checking "Origin", enforcing HTTPS-only "Referer" checks against active network attackers, and unmasking a 64-character base-62 token designed to defeat BREACH compression attacks. Underneath signed cookies, sessions, and reset tokens sits Signer, whose salted_hmac isolates every feature into its own derived key, whose SECRET_KEY_FALLBACKS pays linear verification cost for zero-downtime key rotation, and whose Django 6.1 cookie signer adds length-prefixed v2 salts to close a subtle concatenation collision.
On the way back out, Django 6.1’s built-in ContentSecurityPolicyMiddleware compiles policy dictionaries and injects a 128-bit LazyNonce only when the response actually consumed it; XFrameOptionsMiddleware stamps framing rules; and SafeString plus format_html carry autoescaping across Python string operations — while Django 6.1 now turns a zero-argument format_html(f"...") call into an immediate TypeError.
Finally, every default has a sharp cliff where Django stops and application code owns the entire trust boundary: object-level authorisation, ModelForm allow-lists, raw SQL interpolation, middleware order, and DEBUG = True.
We begin at the very first line of an incoming HTTP request: the "Host" header, TLS detection, and redirects in Allowed hosts, redirects, and proxy headers.