{"title":"Django 的安全性","version":"6.1","locale":"zh-hans","docname":"topics/security","url":"/zh-hans/6.1/topics/security/","canonical":"https://djangodocs.dev/zh-hans/6.1/topics/security/","summary":"此文档是对 Django 安全特性的概述。包含保障那些用 Django 建立的网站的安全性建议。","html":"<h1>Django 的安全性<a class=\"heading-anchor\" href=\"#security-in-django\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h1>\n<p>此文档是对 Django 安全特性的概述。包含保障那些用 Django 建立的网站的安全性建议。</p>\n<aside class=\"admonition-real-world-security admonition\" role=\"note\">\n<p class=\"admonition-title\">Real-world security</p>\n<p>Django's web security implementations have been designed with security for\nreal-world applications in mind. Django is a general-purpose web\napplication framework, and its defaults reflect this - they will not be the\nbest solution for every particular case. Special cases deserve special\nattention to their needs.</p>\n<p>Web security requires a multi-layered approach. Securing only a single\nvector does not make a site secure overall, nor does a single apparent\nweakness necessarily compromise the entire site. This should be borne in\nmind particularly when assessing individual points in security audits.</p>\n</aside>\n<section id=\"always-sanitize-user-input\">\n<span id=\"sanitize-user-input\"></span><h2>Always sanitize user input<a class=\"heading-anchor\" href=\"#always-sanitize-user-input\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h2>\n<p>The golden rule of web application security is to never trust user-controlled\ndata. Hence, all user input should be sanitized before being used in your\napplication. See the <a class=\"reference internal\" href=\"/zh-hans/6.1/topics/forms/\"><span class=\"doc\">forms documentation</span></a> for\ndetails on validating user inputs in Django.</p>\n</section>\n<section id=\"cross-site-scripting-xss-protection\">\n<span id=\"cross-site-scripting\"></span><h2>Cross-site scripting (XSS) protection<a class=\"heading-anchor\" href=\"#cross-site-scripting-xss-protection\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h2>\n<p>In a cross-site scripting attack, malicious code in the form of a client-side\nscript is injected into another user's web browser, where it will be executed.</p>\n<p>This is typically done by:</p>\n<ul class=\"simple\">\n<li><p>storing the malicious script in the database where it will be retrieved and\npresented to other users in their browsers, or</p></li>\n<li><p>getting users to click a link which will cause the attacker's JavaScript to\nbe executed by the user's browser.</p></li>\n</ul>\n<p>Cross-site scripting attacks can originate from any untrusted source of data,\nincluding cookies or web services, if the data are not adequately sanitized\nbefore being published in a page.</p>\n<p>Django templates provide protection against the majority of cross-site\nscripting attacks by <a class=\"reference internal\" href=\"/zh-hans/6.1/ref/templates/language/#automatic-html-escaping\"><span class=\"std std-ref\">automatically escaping characters that represent a\nrisk</span></a> (that is, HTML characters that could be\n<em>interpreted</em> by the browser to malicious effect are instead safely\n<em>displayed</em>).</p>\n<p>However, the extent of this protection and its limitations should be\nunderstood.</p>\n<p>Ambiguity between the developer's intention and how the browser interprets\nHTML can expose the client to unintended code execution. Suppose that a\ndeveloper creates:</p>\n<div class=\"code-block\" data-language=\"text\"><div class=\"code-block-toolbar\"><span class=\"code-block-language\">Text</span><button type=\"button\" class=\"copy-button\" data-copy hidden><span class=\"copy-button-label\">Copy</span></button></div><pre role=\"group\" tabindex=\"0\" aria-label=\"Text code\"><code>&lt;style class={{ var }}&gt;...&lt;/style&gt;\n</code></pre></div>\n<p>where <code class=\"docutils literal notranslate\">var</code> is expected to contain something like <code class=\"docutils literal notranslate\">'class1'</code>. If <code class=\"docutils literal notranslate\">var</code>\nwere set to <code class=\"docutils literal notranslate\">'class1 onmouseover=javascript:func()'</code> though, this could\nresult in unauthorized JavaScript execution due to differences in how browsers\nwill interpret this imperfect HTML.</p>\n<p>Explicit template design, in which the quotes are not left to the variable to\nprovide:</p>\n<div class=\"code-block\" data-language=\"html+django\"><div class=\"code-block-toolbar\"><span class=\"code-block-language\">Django template</span><button type=\"button\" class=\"copy-button\" data-copy hidden><span class=\"copy-button-label\">Copy</span></button></div><pre role=\"group\" tabindex=\"0\" aria-label=\"Django template code\"><code><span class=\"p\">&lt;</span><span class=\"nt\">style</span> <span class=\"na\">class</span><span class=\"o\">=</span><span class=\"s\">&quot;</span><span class=\"cp\">{{</span> <span class=\"nv\">var</span> <span class=\"cp\">}}</span><span class=\"s\">&quot;</span><span class=\"p\">&gt;</span><span class=\"o\">...</span><span class=\"p\">&lt;/</span><span class=\"nt\">style</span><span class=\"p\">&gt;</span>\n</code></pre></div>\n<p>would eliminate this possibility.</p>\n<p>It is also important to be particularly careful when using the <code class=\"docutils literal notranslate\">is_safe</code>\nattribute with custom template tags, the <a class=\"reference internal\" href=\"/zh-hans/6.1/ref/templates/builtins/#std-templatefilter-safe\"><code class=\"xref std std-tfilter docutils literal notranslate\">safe</code></a> template tag,\n<a class=\"reference internal\" href=\"/zh-hans/6.1/ref/utils/#module-django.utils.safestring\" title=\"django.utils.safestring: Functions and classes for working with strings that can be displayed safely without further escaping in HTML.\"><code class=\"xref py py-mod docutils literal notranslate\">mark_safe</code></a>, and when autoescape is turned off.</p>\n<p>Django's built-in escaping is intended to protect HTML output. If you are using\nthe template system to output something other than HTML, the characters and\nstrings that require escaping might be entirely different.</p>\n<p>Additionally, be very careful when storing HTML in the database, especially\nwhen that HTML is retrieved and displayed. Unless the HTML is guaranteed to\ncome from a trusted source - user input is <em>not</em> a trusted source - stored HTML\nshould be checked and sanitized, preferably on input as well as output.</p>\n</section>\n<section id=\"cross-site-request-forgery-csrf-protection\">\n<h2>Cross-site request forgery (CSRF) protection<a class=\"heading-anchor\" href=\"#cross-site-request-forgery-csrf-protection\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h2>\n<p>发起 CSRF 攻击的人可以使用其他用户的证书执行操作，且是在其不知情或不同意的情况下。</p>\n<p>Django 内置了保护措施来防御大多数 CSRF 攻击，您需要在合适的地方 <a class=\"reference internal\" href=\"/zh-hans/6.1/howto/csrf/#using-csrf\"><span class=\"std std-ref\">授权并使用它</span></a>  。但和多数缓解性技术一样，它是有局限性的。比如可以全局禁用 CSRF 模块或者特定的视图。请三思而后行。如果您的网页还有脱离您控制的子域，还将会有其他 <a class=\"reference internal\" href=\"/zh-hans/6.1/ref/csrf/#csrf-limitations\"><span class=\"std std-ref\">限制</span></a> 。</p>\n<p><a class=\"reference internal\" href=\"/zh-hans/6.1/ref/csrf/#how-csrf-works\"><span class=\"std std-ref\">CSRF protection works</span></a> by checking for a secret in each\nPOST request. This ensures that a malicious user cannot &quot;replay&quot; a form POST to\nyour website and have another logged-in user unwittingly submit that form. The\nmalicious user would have to know the secret, which is user specific (using a\ncookie).</p>\n<p>在部署 <a class=\"reference internal\" href=\"#security-recommendation-ssl\"><span class=\"std std-ref\">HTTPS</span></a> 时，<code class=\"docutils literal notranslate\">CsrfViewMiddleware</code> 会检查 HTTP 报文的 referer 首部是否设置为同源的 URL（包括子域和端口）。因为 HTTPS 提供了额外的安全性，所有通过转发不安全连接请求并在支持的浏览器中使用 HSTS 来确保连接在可用的地方使用了 HTTPS ，这一点是很重要的。</p>\n<p>除非绝对需要，否则对视图进行标记 <code class=\"docutils literal notranslate\">csrf_exempt</code> 装饰器时要极其慎重。</p>\n</section>\n<section id=\"sql-injection-protection\">\n<span id=\"id1\"></span><h2>防御 SQL 注入<a class=\"heading-anchor\" href=\"#sql-injection-protection\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h2>\n<p>SQL 注入能让恶意用户能在数据库中执行任意 SQL 代码。这将导致记录被删除或泄露。</p>\n<p>Django 的 querysets 在被参数化查询构建出来时就被保护而免于 SQL 注入。查询的 SQL 代码与查询的参数是分开定义的。参数可能来自用户从而不安全，因此它们由底层数据库引擎进行转义。</p>\n<p>Django 也为开发者提供了书写 <a class=\"reference internal\" href=\"/zh-hans/6.1/topics/db/sql/#executing-raw-queries\"><span class=\"std std-ref\">原始查询</span></a> 或执行 <a class=\"reference internal\" href=\"/zh-hans/6.1/topics/db/sql/#executing-custom-sql\"><span class=\"std std-ref\">自定义 sql</span></a> 的权力。应当尽可能少地使用这些方法，并且您应该小心并准确地转义一切用户可控的参数。另外，在使用 <a class=\"reference internal\" href=\"/zh-hans/6.1/ref/models/querysets/#django.db.models.query.QuerySet.extra\" title=\"django.db.models.query.QuerySet.extra\"><code class=\"xref py py-meth docutils literal notranslate\">extra()</code></a> 和 <a class=\"reference internal\" href=\"/zh-hans/6.1/ref/models/expressions/#django.db.models.expressions.RawSQL\" title=\"django.db.models.expressions.RawSQL\"><code class=\"xref py py-class docutils literal notranslate\">RawSQL</code></a> 时应当小心谨慎。</p>\n</section>\n<section id=\"clickjacking-protection\">\n<h2>防御访问劫持<a class=\"heading-anchor\" href=\"#clickjacking-protection\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h2>\n<p>访问劫持能让恶意网页覆盖另一个网页。可能会有毫不知情的用户被骗入目标网页并执行意料之外的操作。</p>\n<p>Django 包含 <a class=\"reference internal\" href=\"/zh-hans/6.1/ref/clickjacking/#clickjacking-prevention\"><span class=\"std std-ref\">访问劫持保护</span></a> ，以 <a class=\"reference internal\" href=\"/zh-hans/6.1/ref/middleware/#django.middleware.clickjacking.XFrameOptionsMiddleware\" title=\"django.middleware.clickjacking.XFrameOptionsMiddleware\"><code class=\"xref py py-mod docutils literal notranslate\">X-Frame-Options middleware</code></a> 的形式在支持它的浏览器中阻止一个网页被渲染在 frame 的内部。可在每个视图的基础上禁用保护，也可配置发送的确切头部值。</p>\n<p>对于任何不会被第三方网站嵌入 frame 的网页，或者只允许使用一小部分的网页来说，强烈建议使用中间件。</p>\n</section>\n<section id=\"ssl-https\">\n<span id=\"security-recommendation-ssl\"></span><h2>SSL/HTTPS<a class=\"heading-anchor\" href=\"#ssl-https\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h2>\n<p>通过 HTTPS 部署您的网页是保障安全的最佳办法。没有它，恶意用户就可以在客户端和服务器之间嗅探验证资格或其他信息，在某些情况下 -- 比如 <strong>主动</strong> 网络攻击者 -- 会修改发送中的数据。</p>\n<p>如果您想得到 HTTPS 的保护，且已经在您的服务器上启用了，下面还有一些额外的步骤需要执行：</p>\n<ul>\n<li><p>如有必要，设置 <a class=\"reference internal\" href=\"/zh-hans/6.1/ref/settings/#std-setting-SECURE_PROXY_SSL_HEADER\"><code class=\"xref std std-setting docutils literal notranslate\">SECURE_PROXY_SSL_HEADER</code></a>，确保您已经彻底的了解了它的警告提示。如果不这么做，将会导致 CSRF 漏洞，如果操作不正确，也是非常危险的。</p></li>\n<li><p>设置 <a class=\"reference internal\" href=\"/zh-hans/6.1/ref/settings/#std-setting-SECURE_SSL_REDIRECT\"><code class=\"xref std std-setting docutils literal notranslate\">SECURE_SSL_REDIRECT</code></a> 为  <code class=\"docutils literal notranslate\">True</code>，这样 HTTP 的请求就会被重定向到 HTTPS。</p>\n<p>请注意 <a class=\"reference internal\" href=\"/zh-hans/6.1/ref/settings/#std-setting-SECURE_PROXY_SSL_HEADER\"><code class=\"xref std std-setting docutils literal notranslate\">SECURE_PROXY_SSL_HEADER</code></a> 下的注意事项。对于反向代理的情况，配置主 Web 服务器来做重定向到 HTTPS 可能更容易或更安全。</p>\n</li>\n<li><p>使用 'secure' cookies。</p>\n<p>如果浏览器使用默认的 HTTP 来实现初始连接，可能会导致已有的 cookies 泄露。因此，您应当将 <a class=\"reference internal\" href=\"/zh-hans/6.1/ref/settings/#std-setting-CSRF_COOKIE_SECURE\"><code class=\"xref std std-setting docutils literal notranslate\">CSRF_COOKIE_SECURE</code></a> 和 <a class=\"reference internal\" href=\"/zh-hans/6.1/ref/settings/#std-setting-CSRF_COOKIE_SECURE\"><code class=\"xref std std-setting docutils literal notranslate\">CSRF_COOKIE_SECURE</code></a> 设置为 <code class=\"docutils literal notranslate\">True</code>。这样浏览器就会仅用 HTTPS 连接来发送 cookies。注意，这会使得 sessions 不能再通过 HTTP 工作，且 CSRF 防御机制将会阻止任何通过 HTTP 接收到的 POST 数据（当然把所有 HTTP 都弄成 HTTPS 是最好的）。</p>\n</li>\n<li><p>使用 <a class=\"reference internal\" href=\"/zh-hans/6.1/ref/middleware/#http-strict-transport-security\"><span class=\"std std-ref\">HTTP 严格传输安全</span></a> （HSTS）</p>\n<p>HSTS 是一个 HTTP 标头，它通知浏览器，所有未来连接到一个特定的网站应该始终使用 HTTPS。结合重定向 HTTP 请求到 HTTPS，这将确保连接总是享受 SSL 的额外安全，只要有一个成功的连接发生。HSTS 可以通过 <a class=\"reference internal\" href=\"/zh-hans/6.1/ref/settings/#std-setting-SECURE_HSTS_SECONDS\"><code class=\"xref std std-setting docutils literal notranslate\">SECURE_HSTS_SECONDS</code></a>、 <a class=\"reference internal\" href=\"/zh-hans/6.1/ref/settings/#std-setting-SECURE_HSTS_INCLUDE_SUBDOMAINS\"><code class=\"xref std std-setting docutils literal notranslate\">SECURE_HSTS_INCLUDE_SUBDOMAINS</code></a> 和 <a class=\"reference internal\" href=\"/zh-hans/6.1/ref/settings/#std-setting-SECURE_HSTS_PRELOAD\"><code class=\"xref std std-setting docutils literal notranslate\">SECURE_HSTS_PRELOAD</code></a> 来配置，或者在网络服务器上配置。</p>\n</li>\n</ul>\n</section>\n<section id=\"host-header-validation\">\n<span id=\"host-headers-virtual-hosting\"></span><h2>Host 头部验证<a class=\"heading-anchor\" href=\"#host-header-validation\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h2>\n<p>Django uses the <code class=\"docutils literal notranslate\">Host</code> header provided by the client to construct URLs in\ncertain cases. While these values are sanitized to prevent cross-site scripting\nattacks, a fake <code class=\"docutils literal notranslate\">Host</code> value can be used for cross-site request forgery,\ncache poisoning attacks, and poisoning links in emails.</p>\n<p>Because even seemingly-secure web server configurations are susceptible to fake\n<code class=\"docutils literal notranslate\">Host</code> headers, Django validates <code class=\"docutils literal notranslate\">Host</code> headers against the\n<a class=\"reference internal\" href=\"/zh-hans/6.1/ref/settings/#std-setting-ALLOWED_HOSTS\"><code class=\"xref std std-setting docutils literal notranslate\">ALLOWED_HOSTS</code></a> setting in the\n<a class=\"reference internal\" href=\"/zh-hans/6.1/ref/request-response/#django.http.HttpRequest.get_host\" title=\"django.http.HttpRequest.get_host\"><code class=\"xref py py-meth docutils literal notranslate\">django.http.HttpRequest.get_host()</code></a> method.</p>\n<p>This validation only applies via <a class=\"reference internal\" href=\"/zh-hans/6.1/ref/request-response/#django.http.HttpRequest.get_host\" title=\"django.http.HttpRequest.get_host\"><code class=\"xref py py-meth docutils literal notranslate\">get_host()</code></a>;\nif your code accesses the <code class=\"docutils literal notranslate\">Host</code> header directly from <code class=\"docutils literal notranslate\">request.META</code> you\nare bypassing this security protection.</p>\n<p>更多细节请参照完整的 <a class=\"reference internal\" href=\"/zh-hans/6.1/ref/settings/#std-setting-ALLOWED_HOSTS\"><code class=\"xref std std-setting docutils literal notranslate\">ALLOWED_HOSTS</code></a> 文档。</p>\n<aside class=\"admonition admonition-warning\" role=\"note\">\n<p class=\"admonition-title\">Warning</p>\n<p>本文档的较早版本建议配置你的网络服务器，以确保它验证传入的 HTTP <code class=\"docutils literal notranslate\">Host</code> 头。虽然我们现在还是这样建议，但在许多常见 Web 服务器中，看似验证了 <code class=\"docutils literal notranslate\">Host</code> 头的配置，实际上却没有验证。例如，即使 Apache 的配置是让你的 Django 网站从一个非默认的虚拟主机上运行，并设置了 &quot;ServerName&quot;，HTTP 请求仍然有可能匹配这个虚拟主机，并提供一个假的 &quot;Host &quot; 头。因此，Django 现在要求你显式地设置 <a class=\"reference internal\" href=\"/zh-hans/6.1/ref/settings/#std-setting-ALLOWED_HOSTS\"><code class=\"xref std std-setting docutils literal notranslate\">ALLOWED_HOSTS</code></a>，而不是依赖 Web 服务器的配置。</p>\n</aside>\n<p>另外，如果您的配置需要，Django 要求您明确启用对 <code class=\"docutils literal notranslate\">X-Forwarded-Host</code> 标头的支持（通过 <a class=\"reference internal\" href=\"/zh-hans/6.1/ref/settings/#std-setting-USE_X_FORWARDED_HOST\"><code class=\"xref std std-setting docutils literal notranslate\">USE_X_FORWARDED_HOST</code></a> 配置）。</p>\n</section>\n<section id=\"referrer-policy\">\n<h2>Referrer 策略<a class=\"heading-anchor\" href=\"#referrer-policy\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h2>\n<p>浏览器使用 <code class=\"docutils literal notranslate\">Referer</code> 头部来把关于用户是如何到达那里的信息发送到网站。通过设置 <em>Referrer 策略</em>，限制在哪些情况下设置 <code class=\"docutils literal notranslate\">Referer</code> 头部，可以保护您用户的隐私。请看 <a class=\"reference internal\" href=\"/zh-hans/6.1/ref/middleware/#referrer-policy\"><span class=\"std std-ref\">安全中间件参考中的 referrer 策略部分</span></a> 了解更多细节。</p>\n</section>\n<section id=\"cross-origin-opener-policy\">\n<h2>跨源弹出式窗口策略<a class=\"heading-anchor\" href=\"#cross-origin-opener-policy\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h2>\n<p>跨源弹出式窗口策略（COOP）头允许浏览器将一个顶级窗口与其他文档隔离，把它们放在不同的上下文组中，使它们不能直接与顶级窗口交互。如果一个受 COOP 保护的文档打开了一个跨源弹出窗口，该弹出窗口的 <code class=\"docutils literal notranslate\">window.opener</code> 属性将为 <code class=\"docutils literal notranslate\">null</code>。COOP 可以防止跨源攻击。详情请看 <a class=\"reference internal\" href=\"/zh-hans/6.1/ref/middleware/#cross-origin-opener-policy\"><span class=\"std std-ref\">安全中间件参考资料中的跨源弹出式窗口策略部分</span></a>。</p>\n</section>\n<section id=\"cross-origin-resource-sharing-cors\">\n<h2>Cross-origin resource sharing (CORS)<a class=\"heading-anchor\" href=\"#cross-origin-resource-sharing-cors\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h2>\n<p>Cross-Origin Resource Sharing (CORS) controls which origins are permitted to\naccess resources from your site via the browser. Django does not include\nbuilt-in support for CORS headers.</p>\n<aside class=\"admonition-there-are-community-maintained-solutions admonition\" role=\"note\">\n<p class=\"admonition-title\">There are community-maintained solutions!</p>\n<p>Django has a vibrant ecosystem. There are CORS and middleware solutions\nhighlighted on the <a class=\"reference external\" href=\"https://www.djangoproject.com/community/ecosystem/#security-middleware\">Community Ecosystem</a> page. The Django Packages\n<a class=\"reference external\" href=\"https://djangopackages.org/grids/g/security/\">Security grid</a> has even more options for you!</p>\n</aside>\n</section>\n<section id=\"session-security\">\n<h2>会话安全<a class=\"heading-anchor\" href=\"#session-security\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h2>\n<p>类似于 <a class=\"reference internal\" href=\"/zh-hans/6.1/ref/csrf/#csrf-limitations\"><span class=\"std std-ref\">CSRF 限制</span></a> 要求一个被部署的网页应让不受信任的用户不能访问任何子域，<a class=\"reference internal\" href=\"/zh-hans/6.1/topics/http/sessions/#module-django.contrib.sessions\" title=\"django.contrib.sessions: Provides session management for Django projects.\"><code class=\"xref py py-mod docutils literal notranslate\">django.contrib.sessions</code></a> 也有限制。参照 <a class=\"reference internal\" href=\"/zh-hans/6.1/topics/http/sessions/#topics-session-security\"><span class=\"std std-ref\">会话主题指南中关于安全的部分</span></a> 获取更多细节。</p>\n</section>\n<section id=\"user-uploaded-content\">\n<span id=\"user-uploaded-content-security\"></span><h2>用户上传内容<a class=\"heading-anchor\" href=\"#user-uploaded-content\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h2>\n<aside class=\"admonition admonition-note\" role=\"note\">\n<p class=\"admonition-title\">Note</p>\n<p>考虑 <a class=\"reference internal\" href=\"/zh-hans/6.1/howto/static-files/deployment/#staticfiles-from-cdn\"><span class=\"std std-ref\">从云服务或 CDN 提供静态文件服务</span></a> 来避免此类问题。</p>\n</aside>\n<ul>\n<li><p>If your site accepts file uploads, it is strongly advised that you limit\nthese uploads in your web server configuration to a reasonable\nsize in order to prevent denial of service (DOS) attacks. In Apache, this\ncan be easily set using the <a class=\"reference external\" href=\"https://httpd.apache.org/docs/2.4/mod/core.html#limitrequestbody\">LimitRequestBody</a> directive. You should not rely\nsolely on <a class=\"reference internal\" href=\"/zh-hans/6.1/ref/settings/#std-setting-DATA_UPLOAD_MAX_MEMORY_SIZE\"><code class=\"xref std std-setting docutils literal notranslate\">DATA_UPLOAD_MAX_MEMORY_SIZE</code></a>\nnor <a class=\"reference internal\" href=\"/zh-hans/6.1/ref/settings/#std-setting-FILE_UPLOAD_MAX_MEMORY_SIZE\"><code class=\"xref std std-setting docutils literal notranslate\">FILE_UPLOAD_MAX_MEMORY_SIZE</code></a>.</p></li>\n<li><p>如果您为自己的静态文件提供服务，确保像 Apache 的 <code class=\"docutils literal notranslate\">mod_php</code> 这种能把静态文件当作代码来执行的处理程序已经关闭。您绝不会希望用户能够通过上传并请求特制文件来执行任意的代码。</p></li>\n<li><p>如果媒体文件没有遵循安全性最佳惯例，Django 的媒体上传处理会产生一些漏洞。特别的，如果一个 HTML 文件包含合法的 PNG 格式头部并附加一些恶意的 HTML，它是可以作为一个图片文件上传的。该文件将会通过 Django 用于 <a class=\"reference internal\" href=\"/zh-hans/6.1/ref/models/fields/#django.db.models.ImageField\" title=\"django.db.models.ImageField\"><code class=\"xref py py-class docutils literal notranslate\">ImageField</code></a> 图片处理（Pillow）库的验证。当此文件随后被展示给用户时，它可以被显示为 HTML，这取决于您的服务器类型于配置。</p>\n<p>在框架级别上没有防护技术方案可以安全地验证所有用户上传的文件内容，但是您可以采取其他步骤来减轻这些攻击：</p>\n<ol class=\"arabic simple\">\n<li><p>通过一直为来自不同顶级域名或二级域名的用户提供上传内容可以防御一类的攻击。这可以防止被 <a class=\"reference external\" href=\"https://en.wikipedia.org/wiki/Same-origin_policy\">same-origin policy</a> 保护机制阻止的任何攻击，比如跨站脚本攻击。例如您的网站是 <code class=\"docutils literal notranslate\">example.com</code>，您应当通过形如 <code class=\"docutils literal notranslate\">usercontent-example.com</code> 的方式来提供上传内容服务（配置 <a class=\"reference internal\" href=\"/zh-hans/6.1/ref/settings/#std-setting-MEDIA_URL\"><code class=\"xref std std-setting docutils literal notranslate\">MEDIA_URL</code></a>）。仅仅从像 <code class=\"docutils literal notranslate\">usercontent.example.com</code> 这样的子域提供内容是*不够*的。</p></li>\n<li><p>除此之外，应用可以选择定义一个列表来限制允许用户上传的文件的扩展名，并将 Web 服务器配置为仅为此类文件服务。</p></li>\n</ol>\n</li>\n</ul>\n</section>\n<section id=\"form-submissions\">\n<h2>Form Submissions<a class=\"heading-anchor\" href=\"#form-submissions\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h2>\n<ul class=\"simple\">\n<li><p>Form submissions containing files are not limited by\n<a class=\"reference internal\" href=\"/zh-hans/6.1/ref/settings/#std-setting-DATA_UPLOAD_MAX_MEMORY_SIZE\"><code class=\"xref std std-setting docutils literal notranslate\">DATA_UPLOAD_MAX_MEMORY_SIZE</code></a>. Under ASGI, the entire request may be\nspooled to disk before any file size validation is performed. It is strongly\nadvised that you limit the maximum request body size in your web server\nconfiguration to prevent denial of service (DOS) attacks.</p></li>\n</ul>\n</section>\n<section id=\"content-security-policy\">\n<span id=\"security-csp\"></span><h2>Content Security Policy<a class=\"heading-anchor\" href=\"#content-security-policy\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h2>\n<aside class=\"version-note version-added\" data-version=\"6.0\" role=\"note\">\n<p class=\"version-note-title\">New in Django 6.0</p></aside>\n<p>Content Security Policy (CSP) is a browser security mechanism that helps\nprotect web applications against attacks such as cross-site scripting (XSS) and\nother content injection attacks.</p>\n<p>CSP allows web applications to define which sources of content are trusted,\ninstructing the browser to load, execute, or render resources only from those\nsources. This effectively creates an allowlist of content origins, reducing the\nrisk of malicious code execution.</p>\n<p>Key benefits of enabling CSP include:</p>\n<ol class=\"arabic simple\">\n<li><p>Mitigating XSS attacks by blocking inline scripts and restricting external\nscript loading.</p></li>\n<li><p>Controlling which external resources (e.g., images, fonts, stylesheets) can\nbe loaded.</p></li>\n<li><p>Preventing unwanted framing of your site to protect against clickjacking.</p></li>\n<li><p>Reporting violations to a specified endpoint, enabling monitoring and\ndebugging.</p></li>\n</ol>\n<p>For configuration instructions, see the <a class=\"reference internal\" href=\"/zh-hans/6.1/howto/csp/#csp-config\"><span class=\"std std-ref\">Using CSP</span></a>\ndocumentation, and refer to the <a class=\"reference internal\" href=\"/zh-hans/6.1/ref/csp/#csp-overview\"><span class=\"std std-ref\">CSP overview</span></a> for details\non directives and settings.</p>\n<section id=\"limitations-and-considerations\">\n<h3>Limitations and considerations<a class=\"heading-anchor\" href=\"#limitations-and-considerations\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h3>\n<p>While CSP is a powerful security mechanism, it's important to understand its\nlimitations and implications, particularly when used in Django:</p>\n<ul class=\"simple\">\n<li><p>Policy exclusion risks: Avoid excluding specific paths or responses from\nCSP protection. Due to the browser’s same-origin policy, a vulnerability on\nan unprotected page (e.g., one allowing arbitrary script injection) may be\nleveraged to attack protected pages. Excluding <em>any</em> route can significantly\nweaken the site's overall CSP protection.</p></li>\n<li><p>Performance overhead: Although typically negligible, CSP adds some processing\noverhead. Nonce generation involves secure randomness for each applicable\nrequest. For high-traffic applications or resource-constrained environments,\nmeasure the performance impact accordingly.</p></li>\n<li><p>Browser support: While CSP Levels 1 and 2 are widely supported, newer\ndirectives (CSP Level 3+) or complex policy behaviors may vary across\nbrowsers. Test your policy across the environments you intend to support.</p></li>\n</ul>\n<p>Despite these limitations, CSP remains an important and recommended security\nlayer for web applications. Understanding its constraints will help you design\na more effective and reliable deployment.</p>\n</section>\n</section>\n<section id=\"additional-security-topics\">\n<span id=\"id2\"></span><h2>其他安全性相关主题<a class=\"heading-anchor\" href=\"#additional-security-topics\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h2>\n<p>虽然 Django 开箱即提供了良好的安全保护，但正确部署你的应用程序并利用网络服务器、操作系统和其他组件的安全保护仍然很重要。</p>\n<ul class=\"simple\">\n<li><p>确保你的 Python 代码是在网络服务器的根目录之外。这将确保你的 Python 代码不会被意外地作为纯文本提供（或意外地执行）。</p></li>\n<li><p>小心一切 <a class=\"reference internal\" href=\"/zh-hans/6.1/ref/models/fields/#file-upload-security\"><span class=\"std std-ref\">用户上传的文件</span></a>。</p></li>\n<li><p>Django 不会对认证用户的请求进行节流。为了防止针对认证系统的暴力攻击，你可以考虑部署一个 Django 插件或网络服务器模块来节制这些请求。</p></li>\n<li><p>保持您的 <a class=\"reference internal\" href=\"/zh-hans/6.1/ref/settings/#std-setting-SECRET_KEY\"><code class=\"xref std std-setting docutils literal notranslate\">SECRET_KEY</code></a>，以及如果正在使用的话，<a class=\"reference internal\" href=\"/zh-hans/6.1/ref/settings/#std-setting-SECRET_KEY_FALLBACKS\"><code class=\"xref std std-setting docutils literal notranslate\">SECRET_KEY_FALLBACKS</code></a> 保持保密。</p></li>\n<li><p>用防火墙限制缓存系统和数据库的可访问性是个好主意。</p></li>\n<li><p>看一下开源 Web 应用安全计划（OWASP） <a class=\"reference external\" href=\"https://owasp.org/Top10/\">Top 10 list</a> ，它指定了网络应用程序中一些常见的漏洞。尽管 Django 拥有解决某些问题的工具，但在项目设计中必须考虑其他问题。</p></li>\n<li><p>Mozilla 讨论了很多与 <a class=\"reference external\" href=\"https://infosec.mozilla.org/guidelines/web_security.html\">web security</a> 相关的主题。他们的网页还包括适用于任何系统的安全原则。</p></li>\n</ul>\n</section>","rootId":"security-in-django","toc":[{"title":"Always sanitize user input","anchor":"always-sanitize-user-input","children":[]},{"title":"Cross-site scripting (XSS) protection","anchor":"cross-site-scripting-xss-protection","children":[]},{"title":"Cross-site request forgery (CSRF) protection","anchor":"cross-site-request-forgery-csrf-protection","children":[]},{"title":"防御 SQL 注入","anchor":"sql-injection-protection","children":[]},{"title":"防御访问劫持","anchor":"clickjacking-protection","children":[]},{"title":"SSL/HTTPS","anchor":"ssl-https","children":[]},{"title":"Host 头部验证","anchor":"host-header-validation","children":[]},{"title":"Referrer 策略","anchor":"referrer-policy","children":[]},{"title":"跨源弹出式窗口策略","anchor":"cross-origin-opener-policy","children":[]},{"title":"Cross-origin resource sharing (CORS)","anchor":"cross-origin-resource-sharing-cors","children":[]},{"title":"会话安全","anchor":"session-security","children":[]},{"title":"用户上传内容","anchor":"user-uploaded-content","children":[]},{"title":"Form Submissions","anchor":"form-submissions","children":[]},{"title":"Content Security Policy","anchor":"content-security-policy","children":[{"title":"Limitations and considerations","anchor":"limitations-and-considerations","children":[]}]},{"title":"其他安全性相关主题","anchor":"additional-security-topics","children":[]}],"breadcrumbs":[{"docname":"topics/index","title":"使用 Django","url":"/zh-hans/6.1/topics/"}],"prev":{"docname":"topics/pagination","title":"分页","url":"/zh-hans/6.1/topics/pagination/"},"next":{"docname":"topics/performance","title":"性能和优化","url":"/zh-hans/6.1/topics/performance/"},"formats":{"html":"/zh-hans/6.1/topics/security/","markdown":"/zh-hans/6.1/topics/security.md","json":"/zh-hans/6.1/topics/security.json"},"source":"https://github.com/django/django/blob/stable/6.1.x/docs/topics/security.txt","official":"https://docs.djangoproject.com/zh-hans/6.1/topics/security/","inVersions":["6.1","6.0","5.2","5.1","5.0","4.2","4.1","4.0","3.2","3.1","3.0","2.2","2.1","2.0"],"inLocales":["en","sv","zh-hans","ga","fr","ja","id","it","pt-br","ko","es","el","pl"]}