---
django: 6.1.3 (f16e25dcb9fe55734ba4ea2b00ac34405b7df74a)
part: The request
promise: Django handles security for you.
contents: host-and-transport, csrf, signing, csp-and-headers, clickjacking-and-escaping, where-defaults-stop
---

# Security by default

How 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

```text figure=security-cost-and-gates
Security by default: pipeline gates and microsecond cost on Django 6.1.3 (Python 3.14.8)

where each shield fires along one request:
  1. SecurityMiddleware   -> SSL redirect (in), HSTS + nosniff + Referrer-Policy + COOP (out)
  2. CommonMiddleware     -> unconditional get_host() -> ALLOWED_HOSTS gate (400 DisallowedHost)
  3. CsrfViewMiddleware   -> Origin / HTTPS Referer + masked double-submit token check
  4. View / HTML helpers  -> format_html(), SafeString autoescaping, LazyNonce evaluation
  5. Response unwind      -> XFrameOptionsMiddleware (DENY) + ContentSecurityPolicyMiddleware

cumulative per-request latency (1,000 requests x 5 trials, zero-DB WSGI):
  bare MIDDLEWARE=[] (GET)                          71.8 us  (baseline)
  + SecurityMiddleware (GET)                        85.2 us  (+13.3 us)
  + Security + XFrameOptions (GET)                  91.2 us  (+19.4 us)
  + Security + XFO + CSP (LazyNonce unused)         97.2 us  (+25.4 us)
  + Security + XFO + CSP (LazyNonce read)          112.3 us  (+40.5 us)
  + Security + XFO + CSP + Csrf (GET)              109.6 us  (+37.8 us)
  + Security + XFO + CSP + Csrf (verified POST)    157.4 us  (+85.6 us)
```

*Every bar is parsed from `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.get_host` (`django/http/request.py:HttpRequest.get_host`) validates `"Host"` against `ALLOWED_HOSTS`, yet nothing calls it until either `SecurityMiddleware` builds a redirect URL or `CommonMiddleware.process_request` (`django/middleware/common.py:CommonMiddleware.process_request`) 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` (`django/middleware/csrf.py: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` (`django/core/signing.py: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` (`django/middleware/csp.py:ContentSecurityPolicyMiddleware`) compiles policy dictionaries and injects a 128-bit `LazyNonce` only when the response actually consumed it; `XFrameOptionsMiddleware` (`django/middleware/clickjacking.py:XFrameOptionsMiddleware`) stamps framing rules; and `SafeString` (`django/utils/safestring.py:SafeString`) plus `format_html` (`django/utils/html.py: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](security/host-and-transport.md).
