Django의 콘텐츠 보안 정책을 사용하는 방법Link to this heading

기본 구성Link to this heading

Django 프로젝트에서 콘텐츠 보안 정책(CSP)을 활성화하려면 다음을 따르세요.

  1. MIDDLEWARE 설정에 CSP 미들웨어를 추가합니다:

    Code
    MIDDLEWARE = [
        # ...
        "django.middleware.csp.ContentSecurityPolicyMiddleware",
        # ...
    ]
    
  2. ``settings.py``에서 SECURE_CSP 또는 SECURE_CSP_REPORT_ONLY 중 하나(또는 둘 다)를 사용하여 CSP 정책을 설정합니다. :ref:`CSP 설정 문서 <csp-settings>`에서는 두 설정의 차이점을 자세히 설명합니다:

    Code
    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 정책에서 논스를 사용하려면 기본 구성 외에도 다음을 수행해야 합니다.

  1. CSP 설정에 NONCE 플레이스홀더 값을 추가하세요. 이는 script-src 또는 style-src 지시문에만 적용됩니다:

    Code
    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],
    }
    
  2. TEMPLATES 설정에 csp() 컨텍스트 프로세서를 추가하세요. 이렇게 하면 생성된 논스 값을 Django 템플릿에서 csp_nonce 컨텍스트 변수로 사용할 수 있습니다:

    Code
    TEMPLATES = [
        {
            "BACKEND": "django.template.backends.django.DjangoTemplates",
            "OPTIONS": {
                "context_processors": [
                    # ...
                    "django.template.context_processors.csp",
                ],
            },
        },
    ]
    
  3. In your templates, add the nonce to elements that require it:

    For inline <style> or <script> tags, use the csp_nonce context variable directly:

    Django template
    <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 the csp_nonce_attr template tag:

    Django template
    <script src="/path/to/script.js" {% csp_nonce_attr %}></script>
    <link rel="stylesheet" href="/path/to/style.css" {% csp_nonce_attr %}>
    

    To render a Media object’s assets with the nonce applied to each element, pass the object to the csp_nonce_attr tag:

    Django template
    {% csp_nonce_attr form.media %}