Django의 콘텐츠 보안 정책을 사용하는 방법Link to this heading
기본 구성Link to this heading
Django 프로젝트에서 콘텐츠 보안 정책(CSP)을 활성화하려면 다음을 따르세요.
MIDDLEWARE설정에 CSP 미들웨어를 추가합니다:MIDDLEWARE = [ # ... "django.middleware.csp.ContentSecurityPolicyMiddleware", # ... ]``settings.py``에서
SECURE_CSP또는SECURE_CSP_REPORT_ONLY중 하나(또는 둘 다)를 사용하여 CSP 정책을 설정합니다. :ref:`CSP 설정 문서 <csp-settings>`에서는 두 설정의 차이점을 자세히 설명합니다: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/", }
논스 구성Link to this heading
CSP 정책에서 논스를 사용하려면 기본 구성 외에도 다음을 수행해야 합니다.
CSP 설정에
NONCE플레이스홀더 값을 추가하세요. 이는script-src또는style-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], }TEMPLATES설정에csp()컨텍스트 프로세서를 추가하세요. 이렇게 하면 생성된 논스 값을 Django 템플릿에서csp_nonce컨텍스트 변수로 사용할 수 있습니다: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 %}