如何使用 Django 的内容安全策略Link to this heading

基础配置Link to this heading

要在Django项目中启用内容安全策略(CSP):

  1. 将CSP中间件添加到 中间件 设置中:

    Code
    MIDDLEWARE = [
        # ...
        "django.middleware.csp.ContentSecurityPolicyMiddleware",
        # ...
    ]
    
  2. 在settings.py文件中,使用 SECURE_CSPSECURE_CSP_REPORT_ONLY (或两者都使用)来配置CSP策略。CSP设置文档 提供了关于这两者之间差异的更多详细信息:

    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/",
    }
    

Nonce配置Link to this heading

要在CSP策略中使用一次性随机数,即Nonce,除了基本配置外,你还需要:

  1. 在CSP设置中包含 NONCE 占位符值。这仅适用于 script-srcstyle-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. csp() 上下文处理器添加到你的 TEMPLATES 设置中。这样,生成的随机数就会作为``csp_nonce``上下文变量在 Django 模板中可用:

    Code
    TEMPLATES = [
        {
            "BACKEND": "django.template.backends.django.DjangoTemplates",
            "OPTIONS": {
                "context_processors": [
                    # ...
                    "django.template.context_processors.csp",
                ],
            },
        },
    ]
    
  3. 在你的模板中,使用 csp_nonce 上下文变量,将 nonce 属性添加到相关的 <style><script> 内联标签中:

    Django template
    <style nonce="{{ csp_nonce }}">
      /* These inline styles will be allowed. */
    </style>
    
    <script nonce="{{ csp_nonce }}">
      // This inline JavaScript will be allowed.
    </script>