Hur man använder Djangos Content Security PolicyLink to this heading
Grundläggande konfigurationLink to this heading
Så här aktiverar du Content Security Policy (CSP) i ditt Django-projekt:
Lägg till CSP-mellanprogramvaran till din
MIDDLEWARE-inställning:MIDDLEWARE = [ # ... "django.middleware.csp.ContentSecurityPolicyMiddleware", # ... ]Konfigurera CSP-policyerna i din
settings.pymed antingenSECURE_CSPellerSECURE_CSP_REPORT_ONLY(eller båda). CSP-inställningsdokumentationen ger mer information om skillnaderna mellan dessa två: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-konfigurationLink to this heading
För att använda nonces i din CSP-policy måste du, förutom den grundläggande konfigurationen, göra följande:
Inkludera platshållarvärdet
NONCEi CSP-inställningarna. Detta gäller endast direktivenscript-srcellerstyle-src: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], }Lägg till
csp()-kontextprocessorn till dinTEMPLATES-inställning. Detta gör det genererade nonce-värdet tillgängligt i Django-mallarna som kontextvariabelncsp_nonce:TEMPLATES = [ { "BACKEND": "django.template.backends.django.DjangoTemplates", "OPTIONS": { "context_processors": [ # ... "django.template.context_processors.csp", ], }, }, ]I dina mallar lägger du till attributet
noncetill relevanta inline-taggarna<style>eller<script>med hjälp av kontextvariabelncsp_nonce:<style nonce="{{ csp_nonce }}"> /* These inline styles will be allowed. */ </style> <script nonce="{{ csp_nonce }}"> // This inline JavaScript will be allowed. </script>