Django 6.1.3

5.4 Security by default

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 (ContentSecurityPolicyMiddleware, 33 lines) and LazyNonce + build_policy (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, 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:

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):

  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:

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

Now look at LazyNonce and generate_nonce (lines 93–94):

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!

Verify both paths — plus per-view @csp_override — live on Django 6.1.3:

Recorded on Django 6.1.3 ch05-security script
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:

Recorded on Django 6.1.3 ch05-bench script
  + 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:

  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

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.