{"title":"Security in Django","version":"6.0","locale":"en","docname":"topics/security","url":"/en/6.0/topics/security/","canonical":"https://djangodocs.dev/en/6.0/topics/security/","summary":"This document is an overview of Django’s security features. It includes advice on securing a Django-powered site. Always sanitize user input Link to this heading #…","html":"<h1>Security in 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>This document is an overview of Django’s security features. It includes advice\non securing a Django-powered site.</p>\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=\"/en/6.0/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>XSS attacks allow a user to inject client side scripts into the browsers of\nother users. This is usually achieved by storing the malicious scripts in the\ndatabase where it will be retrieved and displayed to other users, or by getting\nusers to click a link which will cause the attacker’s JavaScript to be executed\nby the user’s browser. However, XSS attacks can originate from any untrusted\nsource of data, such as cookies or web services, whenever the data is not\nsufficiently sanitized before including in a page.</p>\n<p>Using Django templates protects you against the majority of XSS attacks.\nHowever, it is important to understand what protections it provides\nand its limitations.</p>\n<p>Django templates <a class=\"reference internal\" href=\"/en/6.0/ref/templates/language/#automatic-html-escaping\"><span class=\"std std-ref\">escape specific characters</span></a>\nwhich are particularly dangerous to HTML. While this protects users from most\nmalicious input, it is not entirely foolproof. For example, it will not\nprotect the following:</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>If <code class=\"docutils literal notranslate\"><span class=\"pre\">var</span></code> is set to <code class=\"docutils literal notranslate\"><span class=\"pre\">'class1</span> <span class=\"pre\">onmouseover=javascript:func()'</span></code>, this can\nresult in unauthorized JavaScript execution, depending on how the browser\nrenders imperfect HTML. (Quoting the attribute value would fix this case.)</p>\n<p>It is also important to be particularly careful when using <code class=\"docutils literal notranslate\"><span class=\"pre\">is_safe</span></code> with\ncustom template tags, the <a class=\"reference internal\" href=\"/en/6.0/ref/templates/builtins/#std-templatefilter-safe\"><code class=\"xref std std-tfilter docutils literal notranslate\"><span class=\"pre\">safe</span></code></a> template tag, <a class=\"reference internal\" href=\"/en/6.0/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\"><span class=\"pre\">mark_safe</span></code></a>, and when autoescape is turned off.</p>\n<p>In addition, if you are using the template system to output something other\nthan HTML, there may be entirely separate characters and words which require\nescaping.</p>\n<p>You should also be very careful when storing HTML in the database, especially\nwhen that HTML is retrieved and displayed.</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 attacks allow a malicious user to execute actions using the credentials\nof another user without that user’s knowledge or consent.</p>\n<p>Django has built-in protection against most types of CSRF attacks, providing\nyou have <a class=\"reference internal\" href=\"/en/6.0/howto/csrf/#using-csrf\"><span class=\"std std-ref\">enabled and used it</span></a> where appropriate. However, as\nwith any mitigation technique, there are limitations. For example, it is\npossible to disable the CSRF module globally or for particular views. You\nshould only do this if you know what you are doing. There are other\n<a class=\"reference internal\" href=\"/en/6.0/ref/csrf/#csrf-limitations\"><span class=\"std std-ref\">limitations</span></a> if your site has subdomains that are\noutside of your control.</p>\n<p><a class=\"reference internal\" href=\"/en/6.0/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 “replay” 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>When deployed with <a class=\"reference internal\" href=\"#security-recommendation-ssl\"><span class=\"std std-ref\">HTTPS</span></a>,\n<code class=\"docutils literal notranslate\"><span class=\"pre\">CsrfViewMiddleware</span></code> will check that the HTTP referer header is set to a\nURL on the same origin (including subdomain and port). Because HTTPS\nprovides additional security, it is imperative to ensure connections use HTTPS\nwhere it is available by forwarding insecure connection requests and using\nHSTS for supported browsers.</p>\n<p>Be very careful with marking views with the <code class=\"docutils literal notranslate\"><span class=\"pre\">csrf_exempt</span></code> decorator unless\nit is absolutely necessary.</p>\n</section>\n<section id=\"sql-injection-protection\">\n<span id=\"id1\"></span><h2>SQL injection protection<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 injection is a type of attack where a malicious user is able to execute\narbitrary SQL code on a database. This can result in records\nbeing deleted or data leakage.</p>\n<p>Django’s querysets are protected from SQL injection since their queries are\nconstructed using query parameterization. A query’s SQL code is defined\nseparately from the query’s parameters. Since parameters may be user-provided\nand therefore unsafe, they are escaped by the underlying database driver.</p>\n<p>Django also gives developers power to write <a class=\"reference internal\" href=\"/en/6.0/topics/db/sql/#executing-raw-queries\"><span class=\"std std-ref\">raw queries</span></a> or execute <a class=\"reference internal\" href=\"/en/6.0/topics/db/sql/#executing-custom-sql\"><span class=\"std std-ref\">custom sql</span></a>.\nThese capabilities should be used sparingly and you should always be careful to\nproperly escape any parameters that the user can control. In addition, you\nshould exercise caution when using\n<a class=\"reference internal\" href=\"/en/6.0/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\"><span class=\"pre\">extra()</span></code></a> and\n<a class=\"reference internal\" href=\"/en/6.0/ref/models/expressions/#django.db.models.expressions.RawSQL\" title=\"django.db.models.expressions.RawSQL\"><code class=\"xref py py-class docutils literal notranslate\"><span class=\"pre\">RawSQL</span></code></a>.</p>\n</section>\n<section id=\"clickjacking-protection\">\n<h2>Clickjacking protection<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>Clickjacking is a type of attack where a malicious site wraps another site\nin a frame. This attack can result in an unsuspecting user being tricked\ninto performing unintended actions on the target site.</p>\n<p>Django contains <a class=\"reference internal\" href=\"/en/6.0/ref/clickjacking/#clickjacking-prevention\"><span class=\"std std-ref\">clickjacking protection</span></a> in the\nform of the <a class=\"reference internal\" href=\"/en/6.0/ref/middleware/#django.middleware.clickjacking.XFrameOptionsMiddleware\" title=\"django.middleware.clickjacking.XFrameOptionsMiddleware\"><code class=\"xref py py-mod docutils literal notranslate\"><span class=\"pre\">X-Frame-Options</span> <span class=\"pre\">middleware</span></code></a> which in a supporting\nbrowser can prevent a site from being rendered inside a frame. It is possible\nto disable the protection on a per view basis or to configure the exact header\nvalue sent.</p>\n<p>The middleware is strongly recommended for any site that does not need to have\nits pages wrapped in a frame by third party sites, or only needs to allow that\nfor a small section of the site.</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>It is always better for security to deploy your site behind HTTPS. Without\nthis, it is possible for malicious network users to sniff authentication\ncredentials or any other information transferred between client and server, and\nin some cases – <strong>active</strong> network attackers – to alter data that is sent in\neither direction.</p>\n<p>If you want the protection that HTTPS provides, and have enabled it on your\nserver, there are some additional steps you may need:</p>\n<ul>\n<li><p>If necessary, set <a class=\"reference internal\" href=\"/en/6.0/ref/settings/#std-setting-SECURE_PROXY_SSL_HEADER\"><code class=\"xref std std-setting docutils literal notranslate\"><span class=\"pre\">SECURE_PROXY_SSL_HEADER</span></code></a>, ensuring that you have\nunderstood the warnings there thoroughly. Failure to do this can result\nin CSRF vulnerabilities, and failure to do it correctly can also be\ndangerous!</p></li>\n<li><p>Set <a class=\"reference internal\" href=\"/en/6.0/ref/settings/#std-setting-SECURE_SSL_REDIRECT\"><code class=\"xref std std-setting docutils literal notranslate\"><span class=\"pre\">SECURE_SSL_REDIRECT</span></code></a> to <code class=\"docutils literal notranslate\"><span class=\"pre\">True</span></code>, so that requests over HTTP\nare redirected to HTTPS.</p>\n<p>Please note the caveats under <a class=\"reference internal\" href=\"/en/6.0/ref/settings/#std-setting-SECURE_PROXY_SSL_HEADER\"><code class=\"xref std std-setting docutils literal notranslate\"><span class=\"pre\">SECURE_PROXY_SSL_HEADER</span></code></a>. For the\ncase of a reverse proxy, it may be easier or more secure to configure the\nmain web server to do the redirect to HTTPS.</p>\n</li>\n<li><p>Use ‘secure’ cookies.</p>\n<p>If a browser connects initially via HTTP, which is the default for most\nbrowsers, it is possible for existing cookies to be leaked. For this reason,\nyou should set your <a class=\"reference internal\" href=\"/en/6.0/ref/settings/#std-setting-SESSION_COOKIE_SECURE\"><code class=\"xref std std-setting docutils literal notranslate\"><span class=\"pre\">SESSION_COOKIE_SECURE</span></code></a> and\n<a class=\"reference internal\" href=\"/en/6.0/ref/settings/#std-setting-CSRF_COOKIE_SECURE\"><code class=\"xref std std-setting docutils literal notranslate\"><span class=\"pre\">CSRF_COOKIE_SECURE</span></code></a> settings to <code class=\"docutils literal notranslate\"><span class=\"pre\">True</span></code>. This instructs the\nbrowser to only send these cookies over HTTPS connections. Note that this\nwill mean that sessions will not work over HTTP, and the CSRF protection will\nprevent any POST data being accepted over HTTP (which will be fine if you are\nredirecting all HTTP traffic to HTTPS).</p>\n</li>\n<li><p>Use <a class=\"reference internal\" href=\"/en/6.0/ref/middleware/#http-strict-transport-security\"><span class=\"std std-ref\">HTTP Strict Transport Security</span></a> (HSTS)</p>\n<p>HSTS is an HTTP header that informs a browser that all future connections to\na particular site should always use HTTPS. Combined with redirecting requests\nover HTTP to HTTPS, this will ensure that connections always enjoy the added\nsecurity of SSL provided one successful connection has occurred. HSTS may\neither be configured with <a class=\"reference internal\" href=\"/en/6.0/ref/settings/#std-setting-SECURE_HSTS_SECONDS\"><code class=\"xref std std-setting docutils literal notranslate\"><span class=\"pre\">SECURE_HSTS_SECONDS</span></code></a>,\n<a class=\"reference internal\" href=\"/en/6.0/ref/settings/#std-setting-SECURE_HSTS_INCLUDE_SUBDOMAINS\"><code class=\"xref std std-setting docutils literal notranslate\"><span class=\"pre\">SECURE_HSTS_INCLUDE_SUBDOMAINS</span></code></a>, and\n<a class=\"reference internal\" href=\"/en/6.0/ref/settings/#std-setting-SECURE_HSTS_PRELOAD\"><code class=\"xref std std-setting docutils literal notranslate\"><span class=\"pre\">SECURE_HSTS_PRELOAD</span></code></a>, or on the web server.</p>\n</li>\n</ul>\n</section>\n<section id=\"host-header-validation\">\n<span id=\"host-headers-virtual-hosting\"></span><h2>Host header validation<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\"><span class=\"pre\">Host</span></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\"><span class=\"pre\">Host</span></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\"><span class=\"pre\">Host</span></code> headers, Django validates <code class=\"docutils literal notranslate\"><span class=\"pre\">Host</span></code> headers against the\n<a class=\"reference internal\" href=\"/en/6.0/ref/settings/#std-setting-ALLOWED_HOSTS\"><code class=\"xref std std-setting docutils literal notranslate\"><span class=\"pre\">ALLOWED_HOSTS</span></code></a> setting in the\n<a class=\"reference internal\" href=\"/en/6.0/ref/request-response/#django.http.HttpRequest.get_host\" title=\"django.http.HttpRequest.get_host\"><code class=\"xref py py-meth docutils literal notranslate\"><span class=\"pre\">django.http.HttpRequest.get_host()</span></code></a> method.</p>\n<p>This validation only applies via <a class=\"reference internal\" href=\"/en/6.0/ref/request-response/#django.http.HttpRequest.get_host\" title=\"django.http.HttpRequest.get_host\"><code class=\"xref py py-meth docutils literal notranslate\"><span class=\"pre\">get_host()</span></code></a>;\nif your code accesses the <code class=\"docutils literal notranslate\"><span class=\"pre\">Host</span></code> header directly from <code class=\"docutils literal notranslate\"><span class=\"pre\">request.META</span></code> you\nare bypassing this security protection.</p>\n<p>For more details see the full <a class=\"reference internal\" href=\"/en/6.0/ref/settings/#std-setting-ALLOWED_HOSTS\"><code class=\"xref std std-setting docutils literal notranslate\"><span class=\"pre\">ALLOWED_HOSTS</span></code></a> documentation.</p>\n<aside class=\"admonition admonition-warning\" role=\"note\">\n<p class=\"admonition-title\">Warning</p>\n<p>Previous versions of this document recommended configuring your web server\nto ensure it validates incoming HTTP <code class=\"docutils literal notranslate\"><span class=\"pre\">Host</span></code> headers. While this is still\nrecommended, in many common web servers a configuration that seems to\nvalidate the <code class=\"docutils literal notranslate\"><span class=\"pre\">Host</span></code> header may not in fact do so. For instance, even if\nApache is configured such that your Django site is served from a non-default\nvirtual host with the <code class=\"docutils literal notranslate\"><span class=\"pre\">ServerName</span></code> set, it is still possible for an HTTP\nrequest to match this virtual host and supply a fake <code class=\"docutils literal notranslate\"><span class=\"pre\">Host</span></code> header. Thus,\nDjango now requires that you set <a class=\"reference internal\" href=\"/en/6.0/ref/settings/#std-setting-ALLOWED_HOSTS\"><code class=\"xref std std-setting docutils literal notranslate\"><span class=\"pre\">ALLOWED_HOSTS</span></code></a> explicitly rather\nthan relying on web server configuration.</p>\n</aside>\n<p>Additionally, Django requires you to explicitly enable support for the\n<code class=\"docutils literal notranslate\"><span class=\"pre\">X-Forwarded-Host</span></code> header (via the <a class=\"reference internal\" href=\"/en/6.0/ref/settings/#std-setting-USE_X_FORWARDED_HOST\"><code class=\"xref std std-setting docutils literal notranslate\"><span class=\"pre\">USE_X_FORWARDED_HOST</span></code></a> setting)\nif your configuration requires it.</p>\n</section>\n<section id=\"referrer-policy\">\n<h2>Referrer policy<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>Browsers use the <code class=\"docutils literal notranslate\"><span class=\"pre\">Referer</span></code> header as a way to send information to a site\nabout how users got there. By setting a <em>Referrer Policy</em> you can help to\nprotect the privacy of your users, restricting under which circumstances the\n<code class=\"docutils literal notranslate\"><span class=\"pre\">Referer</span></code> header is set. See <a class=\"reference internal\" href=\"/en/6.0/ref/middleware/#referrer-policy\"><span class=\"std std-ref\">the referrer policy section of the\nsecurity middleware reference</span></a> for details.</p>\n</section>\n<section id=\"cross-origin-opener-policy\">\n<h2>Cross-origin opener policy<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>The cross-origin opener policy (COOP) header allows browsers to isolate a\ntop-level window from other documents by putting them in a different context\ngroup so that they cannot directly interact with the top-level window. If a\ndocument protected by COOP opens a cross-origin popup window, the popup’s\n<code class=\"docutils literal notranslate\"><span class=\"pre\">window.opener</span></code> property will be <code class=\"docutils literal notranslate\"><span class=\"pre\">null</span></code>. COOP protects against cross-origin\nattacks. See <a class=\"reference internal\" href=\"/en/6.0/ref/middleware/#cross-origin-opener-policy\"><span class=\"std std-ref\">the cross-origin opener policy section of the security\nmiddleware reference</span></a> for details.</p>\n</section>\n<section id=\"session-security\">\n<h2>Session security<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>Similar to the <a class=\"reference internal\" href=\"/en/6.0/ref/csrf/#csrf-limitations\"><span class=\"std std-ref\">CSRF limitations</span></a> requiring a site to\nbe deployed such that untrusted users don’t have access to any subdomains,\n<a class=\"reference internal\" href=\"/en/6.0/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\"><span class=\"pre\">django.contrib.sessions</span></code></a> also has limitations. See <a class=\"reference internal\" href=\"/en/6.0/topics/http/sessions/#topics-session-security\"><span class=\"std std-ref\">the session\ntopic guide section on security</span></a> for details.</p>\n</section>\n<section id=\"user-uploaded-content\">\n<span id=\"user-uploaded-content-security\"></span><h2>User-uploaded content<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>Consider <a class=\"reference internal\" href=\"/en/6.0/howto/static-files/deployment/#staticfiles-from-cdn\"><span class=\"std std-ref\">serving static files from a cloud service or CDN</span></a> to avoid some of these issues.</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=\"/en/6.0/ref/settings/#std-setting-DATA_UPLOAD_MAX_MEMORY_SIZE\"><code class=\"xref std std-setting docutils literal notranslate\"><span class=\"pre\">DATA_UPLOAD_MAX_MEMORY_SIZE</span></code></a>\nnor <a class=\"reference internal\" href=\"/en/6.0/ref/settings/#std-setting-FILE_UPLOAD_MAX_MEMORY_SIZE\"><code class=\"xref std std-setting docutils literal notranslate\"><span class=\"pre\">FILE_UPLOAD_MAX_MEMORY_SIZE</span></code></a>.</p></li>\n<li><p>If you are serving your own static files, be sure that handlers like Apache’s\n<code class=\"docutils literal notranslate\"><span class=\"pre\">mod_php</span></code>, which would execute static files as code, are disabled. You\ndon’t want users to be able to execute arbitrary code by uploading and\nrequesting a specially crafted file.</p></li>\n<li><p>Django’s media upload handling poses some vulnerabilities when that media is\nserved in ways that do not follow security best practices. Specifically, an\nHTML file can be uploaded as an image if that file contains a valid PNG\nheader followed by malicious HTML. This file will pass verification of the\nlibrary that Django uses for <a class=\"reference internal\" href=\"/en/6.0/ref/models/fields/#django.db.models.ImageField\" title=\"django.db.models.ImageField\"><code class=\"xref py py-class docutils literal notranslate\"><span class=\"pre\">ImageField</span></code></a> image\nprocessing (Pillow). When this file is subsequently displayed to a\nuser, it may be displayed as HTML depending on the type and configuration of\nyour web server.</p>\n<p>No bulletproof technical solution exists at the framework level to safely\nvalidate all user uploaded file content, however, there are some other steps\nyou can take to mitigate these attacks:</p>\n<ol class=\"arabic simple\">\n<li><p>One class of attacks can be prevented by always serving user uploaded\ncontent from a distinct top-level or second-level domain. This prevents\nany exploit blocked by <a class=\"reference external\" href=\"https://en.wikipedia.org/wiki/Same-origin_policy\">same-origin policy</a> protections such as cross\nsite scripting. For example, if your site runs on <code class=\"docutils literal notranslate\"><span class=\"pre\">example.com</span></code>, you\nwould want to serve uploaded content (the <a class=\"reference internal\" href=\"/en/6.0/ref/settings/#std-setting-MEDIA_URL\"><code class=\"xref std std-setting docutils literal notranslate\"><span class=\"pre\">MEDIA_URL</span></code></a> setting)\nfrom something like <code class=\"docutils literal notranslate\"><span class=\"pre\">usercontent-example.com</span></code>. It’s <em>not</em> sufficient to\nserve content from a subdomain like <code class=\"docutils literal notranslate\"><span class=\"pre\">usercontent.example.com</span></code>.</p></li>\n<li><p>Beyond this, applications may choose to define a list of allowable\nfile extensions for user uploaded files and configure the web server\nto only serve such files.</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=\"/en/6.0/ref/settings/#std-setting-DATA_UPLOAD_MAX_MEMORY_SIZE\"><code class=\"xref std std-setting docutils literal notranslate\"><span class=\"pre\">DATA_UPLOAD_MAX_MEMORY_SIZE</span></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\">\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=\"/en/6.0/howto/csp/#csp-config\"><span class=\"std std-ref\">Using CSP</span></a>\ndocumentation, and refer to the <a class=\"reference internal\" href=\"/en/6.0/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>Additional security topics<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>While Django provides good security protection out of the box, it is still\nimportant to properly deploy your application and take advantage of the\nsecurity protection of the web server, operating system and other components.</p>\n<ul class=\"simple\">\n<li><p>Make sure that your Python code is outside of the web server’s root. This\nwill ensure that your Python code is not accidentally served as plain text\n(or accidentally executed).</p></li>\n<li><p>Take care with any <a class=\"reference internal\" href=\"/en/6.0/ref/models/fields/#file-upload-security\"><span class=\"std std-ref\">user uploaded files</span></a>.</p></li>\n<li><p>Django does not throttle requests to authenticate users. To protect against\nbrute-force attacks against the authentication system, you may consider\ndeploying a Django plugin or web server module to throttle these requests.</p></li>\n<li><p>Keep your <a class=\"reference internal\" href=\"/en/6.0/ref/settings/#std-setting-SECRET_KEY\"><code class=\"xref std std-setting docutils literal notranslate\"><span class=\"pre\">SECRET_KEY</span></code></a>, and <a class=\"reference internal\" href=\"/en/6.0/ref/settings/#std-setting-SECRET_KEY_FALLBACKS\"><code class=\"xref std std-setting docutils literal notranslate\"><span class=\"pre\">SECRET_KEY_FALLBACKS</span></code></a> if in\nuse, secret.</p></li>\n<li><p>It is a good idea to limit the accessibility of your caching system and\ndatabase using a firewall.</p></li>\n<li><p>Take a look at the Open Web Application Security Project (OWASP) <a class=\"reference external\" href=\"https://owasp.org/Top10/\">Top 10\nlist</a> which identifies some common vulnerabilities in web applications.\nWhile Django has tools to address some of the issues, other issues must be\naccounted for in the design of your project.</p></li>\n<li><p>Mozilla discusses various topics regarding <a class=\"reference external\" href=\"https://infosec.mozilla.org/guidelines/web_security.html\">web security</a>. Their\npages also include security principles that apply to any system.</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 injection protection","anchor":"sql-injection-protection","children":[]},{"title":"Clickjacking protection","anchor":"clickjacking-protection","children":[]},{"title":"SSL/HTTPS","anchor":"ssl-https","children":[]},{"title":"Host header validation","anchor":"host-header-validation","children":[]},{"title":"Referrer policy","anchor":"referrer-policy","children":[]},{"title":"Cross-origin opener policy","anchor":"cross-origin-opener-policy","children":[]},{"title":"Session security","anchor":"session-security","children":[]},{"title":"User-uploaded content","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":"Additional security topics","anchor":"additional-security-topics","children":[]}],"breadcrumbs":[{"docname":"topics/index","title":"Using Django","url":"/en/6.0/topics/"}],"prev":{"docname":"topics/pagination","title":"Pagination","url":"/en/6.0/topics/pagination/"},"next":{"docname":"topics/performance","title":"Performance and optimization","url":"/en/6.0/topics/performance/"},"formats":{"html":"/en/6.0/topics/security/","markdown":"/en/6.0/topics/security.md","json":"/en/6.0/topics/security.json"},"source":"https://github.com/django/django/blob/stable/6.0.x/docs/topics/security.txt","official":"https://docs.djangoproject.com/en/6.0/topics/security/","inVersions":["dev","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","1.11","1.10","1.9","1.8"],"inLocales":["en","sv","zh-hans","ga","fr","ja","id","it","pt-br","ko","es","el","pl"]}