---
django: 6.1.3 (f16e25dcb9fe55734ba4ea2b00ac34405b7df74a)
---

# Content Security Policy and browser headers

How does Django 6's built-in `ContentSecurityPolicyMiddleware` compile policy dictionaries and inject per-request nonces lazily?

Even when every template autoescapes variables, a single unsafe `mark_safe` call or third-party widget can smuggle an inline `<script>` into HTML. Content Security Policy (CSP) adds a second barrier enforced inside the browser itself: an HTTP response header telling the browser which origins — and which specific inline scripts carrying a per-request cryptographic nonce — are allowed to execute.

For more than a decade, Django teams wired this up with third-party packages like `django-csp`. Starting in Django `6.0` (and refined in `6.1.3`), CSP lives directly inside core across two tiny, tightly engineered modules: **`ContentSecurityPolicyMiddleware`** (`django/middleware/csp.py:ContentSecurityPolicyMiddleware`, 33 lines) and **`LazyNonce`** + `build_policy` (`django/utils/csp.py:LazyNonce`, 128 lines).

## Policy dictionaries, the `CSP` `enum.StrEnum`, and deterministic compilation

Open `django/utils/csp.py`. Rather than asking projects to concatenate raw header strings (where missing single quotes around `'self'` or `'none'` silently turns a keyword into a hostname!), Django defines `CSP` (`django/utils/csp.py:CSP`), an `enum.StrEnum` carrying both the two header names (`CSP.HEADER_ENFORCE`, `CSP.HEADER_REPORT_ONLY`), the standard quoted keywords (`CSP.NONE = "'none'"`, `CSP.SELF = "'self'"`, `CSP.STRICT_DYNAMIC = "'strict-dynamic'"`), and a special sentinel `CSP.NONCE = "<CSP_NONCE_SENTINEL>"`.

In `settings.py`, you declare `SECURE_CSP` (enforced) and/or `SECURE_CSP_REPORT_ONLY` (audit mode) as ordinary Python dictionaries mapping directives to iterables:

```python
SECURE_CSP = {
    "default-src": [CSP.SELF],
    "script-src": [CSP.SELF, CSP.NONCE],
}
```

When the response unwinds through `ContentSecurityPolicyMiddleware.process_response`, Django calls `build_policy(config, nonce)` (`django/utils/csp.py:build_policy`):

1. Directives set to `None` or `False` are skipped cleanly (making per-environment overrides trivial).
2. Directives set to `True` emit valueless directives such as `"upgrade-insecure-requests"`.
3. **If a directive's values are given as a Python `set`, line 110 calls `sorted(values)`.** Why bother sorting? Because Python's per-process hash randomization would otherwise shuffle the order of directive sources between worker restarts, breaking ETag stability and proxy caching!
4. If `CSP.NONCE` appears in the directive's values, line 116 checks **`if (has_sentinel := CSP.NONCE in values) and nonce:`**. That `and nonce` test is where the real elegance of Django `6.1`'s design lives.

## How `LazyNonce` avoids CSPRNG work on pages that need no nonce

Generating a cryptographic nonce on every single request (static JSON APIs, redirects, images, HTML pages with no inline scripts) wastes entropy and breaks deterministic caching by injecting a unique random header into every response.

Look at `ContentSecurityPolicyMiddleware.process_request` (`django/middleware/csp.py:ContentSecurityPolicyMiddleware.process_request`):

```python
def process_request(self, request):
    request._csp_nonce = LazyNonce()
```

Now look at `LazyNonce` (`django/utils/csp.py:LazyNonce`) and `generate_nonce` (lines 93–94):

```python
class LazyNonce(SimpleLazyObject):
    def __init__(self):
        super().__init__(generate_nonce)

    def __bool__(self):
        return self._wrapped is not empty

def generate_nonce():
    return secrets.token_urlsafe(16)
```

Read those six lines twice — they are a textbook use of Python's descriptor and truthiness protocol!

- Creating `LazyNonce()` allocates only a lightweight `SimpleLazyObject` wrapper with `_wrapped = empty`. It does **not** call `secrets.token_urlsafe(16)`.
- Unlike ordinary `SimpleLazyObject` (whose `__bool__` forces evaluation of the wrapped object), `LazyNonce.__bool__` **overrides truthiness without evaluating the lazy object**: it simply checks `self._wrapped is not empty`!
- If the view or template never coerces `"csp_nonce"` (exposed via `django.template.context_processors.csp`, `django/template/context_processors.py:csp`, or `get_nonce(request)`) into a string, `_wrapped` stays `empty`. When `build_policy` later tests `and nonce`, `bool(nonce)` returns **`False`**, so `build_policy` **strips `CSP.NONCE` right out of the header** — emitting `"default-src 'self'; script-src 'self'"` with zero CSPRNG calls and a completely static header!
- The instant a template renders `<script nonce="{{ csp_nonce }}">` (or `{% csp_nonce_attr %}` via `nonce_attr`, `django/utils/csp.py:nonce_attr`), string conversion triggers `SimpleLazyObject._setup()`, which calls `secrets.token_urlsafe(16)` — 16 random bytes = 128 bits of entropy = a 22-character URL-safe base64 token — and caches it in `_wrapped`. Now `bool(nonce)` is `True`, and `build_policy` replaces `CSP.NONCE` with `"'nonce-<token>'"`!

Verify both paths — plus per-view `@csp_override` (`django/views/decorators/csp.py:csp_override`) — live on Django `6.1.3`:

```text recording=ch05-security
Django 6 ContentSecurityPolicyMiddleware and LazyNonce
  view does NOT read csp_nonce -> bool_in_view=False  Content-Security-Policy="default-src 'self'; script-src 'self'"
  view READS csp_nonce         -> before=False after=True len=22  nonce_in_header=True  Content-Security-Policy="default-src 'self'; script-src 'self' 'nonce-<22-char-nonce>'"
  @csp_override(default-src 'none') -> Content-Security-Policy="default-src 'none'"
```

And check the microsecond cost we measured in `ch05-bench`:

```text recording=ch05-bench
  + Security + XFrameOptions (GET)                   91.2   +  19.4
  + Security + XFO + CSP (nonce unused)              97.2   +  25.4
  + Security + XFO + CSP (nonce read)               112.3   +  40.5
```

When a view leaves `LazyNonce` unread, `ContentSecurityPolicyMiddleware` adds just **`+6.0 us`** (`91.2 -> 97.2 us`). Reading the nonce costs **`+15.1 us`** (`97.2 -> 112.3 us`) for `secrets.token_urlsafe(16)` and header interpolation.

## Per-view overrides and `StreamingHttpResponse` timing

Look at `ContentSecurityPolicyMiddleware.process_response` (`django/middleware/csp.py:ContentSecurityPolicyMiddleware.process_response`):

1. It uses a fresh `sentinel = object()` to check `getattr(response, "_csp_config", sentinel)` — distinguishing *"this view used `@csp_override({})` to suppress the header entirely"* (remember Chapter 4's `technical_500_response`!) from *"this view set no override, so fall back to `settings.SECURE_CSP`"*.
2. It honors `header not in response`, so a view that sets `response.headers["Content-Security-Policy"]` directly is never overwritten.
3. Because `process_response` runs **after** the view returns (and for a `TemplateResponse`, after template rendering completes), any nonce read inside the template is already evaluated by the time `build_policy` runs.

## Where CSP and `LazyNonce` leak

- **Caching a page that rendered `"csp_nonce"` breaks every subsequent visitor.** Because a nonce must be fresh on every response, serving a cached HTML document carrying yesterday's `<script nonce="abc...">` alongside a response header carrying *today's* nonce (or no nonce at all) causes the browser to block all of your own scripts. Never cache responses that evaluate `LazyNonce` in a shared cache.
- **Reading `"csp_nonce"` inside a `StreamingHttpResponse` generator happens too late.** `process_response` runs and writes the HTTP headers *before* WSGI/ASGI starts iterating the streaming body. If a streaming generator touches `"csp_nonce"` lazily while yielding chunks, `bool(nonce)` was still `False` when `build_policy` ran — so the response header has no nonce and the browser blocks the streamed `<script>`. Force `str(get_nonce(request))` before returning the `StreamingHttpResponse`.
- **`if csp_nonce:` in Python or template code checks whether the nonce was *already* evaluated, not whether CSP middleware is installed.** That behavior is intentional (`LazyNonce.__bool__` lets third-party libraries emit `nonce="..."` only if the page already opted in), yet developers who write `if get_nonce(request):` expecting a truthy check for "is CSP enabled?" get `False`! Check `get_nonce(request) is not None` instead.

CSP restricts what scripts a browser will run if HTML is injected; the next section examines how Django prevents framing attacks and stops raw HTML injection from entering your templates in the first place: [Framing rules and safe strings](clickjacking-and-escaping.md).
