How to use Django's Content Security PolicyLink to this heading
Basic configLink to this heading
To enable Content Security Policy (CSP) in your Django project:
Add the CSP middleware to your
MIDDLEWAREsetting:MIDDLEWARE = [ # ... "django.middleware.csp.ContentSecurityPolicyMiddleware", # ... ]Configure the CSP policies in your
settings.pyusing eitherSECURE_CSPorSECURE_CSP_REPORT_ONLY(or both). The CSP Settings docs provide more details about the differences between these two:from django.utils.csp import CSP # To enforce a CSP policy: SECURE_CSP = { "default-src": [CSP.SELF], # Add more directives to be enforced. } # Or for report-only mode: SECURE_CSP_REPORT_ONLY = { "default-src": [CSP.SELF], # Add more directives as needed. "report-uri": "/path/to/reports-endpoint/", }
Nonce configLink to this heading
To use nonces in your CSP policy, beside the basic config, you need to:
Include the
NONCEplaceholder value in the CSP settings. This only applies toscript-srcorstyle-srcdirectives:from django.utils.csp import CSP SECURE_CSP = { "default-src": [CSP.SELF], # Allow self-hosted scripts and script tags with matching `nonce` attr. "script-src": [CSP.SELF, CSP.NONCE], # Example of the less secure 'unsafe-inline' option. "style-src": [CSP.SELF, CSP.UNSAFE_INLINE], }Add the
csp()context processor to yourTEMPLATESsetting. This makes the generated nonce value available in the Django templates as thecsp_noncecontext variable:TEMPLATES = [ { "BACKEND": "django.template.backends.django.DjangoTemplates", "OPTIONS": { "context_processors": [ # ... "django.template.context_processors.csp", ], }, }, ]In your templates, add the nonce to elements that require it:
For inline
<style>or<script>tags, use thecsp_noncecontext variable directly:<style nonce="{{ csp_nonce }}"> /* These inline styles will be allowed. */ </style> <script nonce="{{ csp_nonce }}"> // This inline JavaScript will be allowed. </script>For external
<script src="...">and<link rel="stylesheet">elements, use thecsp_nonce_attrtemplate tag:<script src="/path/to/script.js" {% csp_nonce_attr %}></script> <link rel="stylesheet" href="/path/to/style.css" {% csp_nonce_attr %}>To render a
Mediaobject's assets with the nonce applied to each element, pass the object to thecsp_nonce_attrtag:{% csp_nonce_attr form.media %}