| 1 |
========== |
| 2 |
Middleware |
| 3 |
========== |
| 4 |
|
| 5 |
.. module:: django.middleware |
| 6 |
:synopsis: Django's built-in middleware classes. |
| 7 |
|
| 8 |
This document explains all middleware components that come with Django. For |
| 9 |
information on how to use them and how to write your own middleware, see |
| 10 |
the :doc:`middleware usage guide </topics/http/middleware>`. |
| 11 |
|
| 12 |
Available middleware |
| 13 |
==================== |
| 14 |
|
| 15 |
Cache middleware |
| 16 |
---------------- |
| 17 |
|
| 18 |
.. module:: django.middleware.cache |
| 19 |
:synopsis: Middleware for the site-wide cache. |
| 20 |
|
| 21 |
.. class:: UpdateCacheMiddleware |
| 22 |
|
| 23 |
.. class:: FetchFromCacheMiddleware |
| 24 |
|
| 25 |
Enable the site-wide cache. If these are enabled, each Django-powered page will |
| 26 |
be cached for as long as the :setting:`CACHE_MIDDLEWARE_SECONDS` setting |
| 27 |
defines. See the :doc:`cache documentation </topics/cache>`. |
| 28 |
|
| 29 |
"Common" middleware |
| 30 |
------------------- |
| 31 |
|
| 32 |
.. module:: django.middleware.common |
| 33 |
:synopsis: Middleware adding "common" conveniences for perfectionists. |
| 34 |
|
| 35 |
.. class:: CommonMiddleware |
| 36 |
|
| 37 |
.. attribute:: response_redirect_class |
| 38 |
|
| 39 |
Defaults to :class:`~django.http.HttpResponsePermanentRedirect`. Subclass |
| 40 |
``CommonMiddleware`` and override the attribute to customize the redirects |
| 41 |
issued by the middleware. |
| 42 |
|
| 43 |
Adds a few conveniences for perfectionists: |
| 44 |
|
| 45 |
* Forbids access to user agents in the :setting:`DISALLOWED_USER_AGENTS` |
| 46 |
setting, which should be a list of compiled regular expression objects. |
| 47 |
|
| 48 |
* Performs URL rewriting based on the :setting:`APPEND_SLASH` and |
| 49 |
:setting:`PREPEND_WWW` settings. |
| 50 |
|
| 51 |
If :setting:`APPEND_SLASH` is ``True`` and the initial URL doesn't end |
| 52 |
with a slash, and it is not found in the URLconf, then a new URL is |
| 53 |
formed by appending a slash at the end. If this new URL is found in the |
| 54 |
URLconf, then Django redirects the request to this new URL. Otherwise, |
| 55 |
the initial URL is processed as usual. |
| 56 |
|
| 57 |
For example, ``foo.com/bar`` will be redirected to ``foo.com/bar/`` if |
| 58 |
you don't have a valid URL pattern for ``foo.com/bar`` but *do* have a |
| 59 |
valid pattern for ``foo.com/bar/``. |
| 60 |
|
| 61 |
If :setting:`PREPEND_WWW` is ``True``, URLs that lack a leading "www." |
| 62 |
will be redirected to the same URL with a leading "www." |
| 63 |
|
| 64 |
Both of these options are meant to normalize URLs. The philosophy is that |
| 65 |
each URL should exist in one, and only one, place. Technically a URL |
| 66 |
``foo.com/bar`` is distinct from ``foo.com/bar/`` -- a search-engine |
| 67 |
indexer would treat them as separate URLs -- so it's best practice to |
| 68 |
normalize URLs. |
| 69 |
|
| 70 |
If necessary, individual views may be excluded from the ``APPEND_SLASH`` |
| 71 |
behavior using the :func:`~django.views.decorators.common.no_append_slash` |
| 72 |
decorator:: |
| 73 |
|
| 74 |
from django.views.decorators.common import no_append_slash |
| 75 |
|
| 76 |
|
| 77 |
@no_append_slash |
| 78 |
def sensitive_fbv(request, *args, **kwargs): |
| 79 |
"""View to be excluded from APPEND_SLASH.""" |
| 80 |
return HttpResponse() |
| 81 |
|
| 82 |
* Sets the ``Content-Length`` header for non-streaming responses. |
| 83 |
|
| 84 |
.. class:: BrokenLinkEmailsMiddleware |
| 85 |
|
| 86 |
* Sends broken link notification emails to :setting:`MANAGERS` (see |
| 87 |
:doc:`/howto/error-reporting`). |
| 88 |
|
| 89 |
GZip middleware |
| 90 |
--------------- |
| 91 |
|
| 92 |
.. module:: django.middleware.gzip |
| 93 |
:synopsis: Middleware to serve GZipped content for performance. |
| 94 |
|
| 95 |
.. class:: GZipMiddleware |
| 96 |
|
| 97 |
.. attribute:: max_random_bytes |
| 98 |
|
| 99 |
Defaults to 100. Subclass ``GZipMiddleware`` and override the attribute |
| 100 |
to change the maximum number of random bytes that is included with |
| 101 |
compressed responses. |
| 102 |
|
| 103 |
.. note:: |
| 104 |
|
| 105 |
Security researchers revealed that when compression techniques (including |
| 106 |
``GZipMiddleware``) are used on a website, the site may become exposed to a |
| 107 |
number of possible attacks. |
| 108 |
|
| 109 |
To mitigate attacks, Django implements a technique called *Heal The Breach |
| 110 |
(HTB)*. It adds up to 100 bytes (see |
| 111 |
:attr:`.max_random_bytes`) of random bytes to each response |
| 112 |
to make the attacks less effective. |
| 113 |
|
| 114 |
For more details, see the `BREACH paper (PDF)`_, `breachattack.com`_, and |
| 115 |
the `Heal The Breach (HTB) paper`_. |
| 116 |
|
| 117 |
.. _BREACH paper (PDF): https://www.breachattack.com/resources/BREACH%20-%20SSL,%20gone%20in%2030%20seconds.pdf |
| 118 |
.. _breachattack.com: https://www.breachattack.com/ |
| 119 |
.. _Heal The Breach (HTB) paper: https://ieeexplore.ieee.org/document/9754554 |
| 120 |
|
| 121 |
The ``django.middleware.gzip.GZipMiddleware`` compresses content for browsers |
| 122 |
that understand GZip compression (all modern browsers). |
| 123 |
|
| 124 |
This middleware should be placed before any other middleware that need to |
| 125 |
read or write the response body so that compression happens afterward. |
| 126 |
|
| 127 |
It will NOT compress content if any of the following are true: |
| 128 |
|
| 129 |
* The content body is less than 200 bytes long. |
| 130 |
|
| 131 |
* The response has already set the ``Content-Encoding`` header. |
| 132 |
|
| 133 |
* The request (the browser) hasn't sent an ``Accept-Encoding`` header |
| 134 |
containing ``gzip``. |
| 135 |
|
| 136 |
If the response has an ``ETag`` header, the ETag is made weak to comply with |
| 137 |
:rfc:`9110#section-8.8.1`. |
| 138 |
|
| 139 |
You can apply GZip compression to individual views using the |
| 140 |
:func:`~django.views.decorators.gzip.gzip_page()` decorator. |
| 141 |
|
| 142 |
Conditional GET middleware |
| 143 |
-------------------------- |
| 144 |
|
| 145 |
.. module:: django.middleware.http |
| 146 |
:synopsis: Middleware handling advanced HTTP features. |
| 147 |
|
| 148 |
.. class:: ConditionalGetMiddleware |
| 149 |
|
| 150 |
Handles conditional GET operations. If the response doesn't have an ``ETag`` |
| 151 |
header, the middleware adds one if needed. If the response has an ``ETag`` or |
| 152 |
``Last-Modified`` header, and the request has ``If-None-Match`` or |
| 153 |
``If-Modified-Since``, the response is replaced by an |
| 154 |
:class:`~django.http.HttpResponseNotModified`. |
| 155 |
|
| 156 |
You can handle conditional GET operations with individual views using the |
| 157 |
:func:`~django.views.decorators.http.conditional_page()` decorator. |
| 158 |
|
| 159 |
Locale middleware |
| 160 |
----------------- |
| 161 |
|
| 162 |
.. module:: django.middleware.locale |
| 163 |
:synopsis: Middleware to enable language selection based on the request. |
| 164 |
|
| 165 |
.. class:: LocaleMiddleware |
| 166 |
|
| 167 |
.. attribute:: LocaleMiddleware.response_redirect_class |
| 168 |
|
| 169 |
Defaults to :class:`~django.http.HttpResponseRedirect`. Subclass |
| 170 |
``LocaleMiddleware`` and override the attribute to customize the |
| 171 |
redirects issued by the middleware. |
| 172 |
|
| 173 |
Enables language selection based on data from the request. It customizes |
| 174 |
content for each user. See the :doc:`internationalization documentation |
| 175 |
</topics/i18n/translation>`. |
| 176 |
|
| 177 |
Message middleware |
| 178 |
------------------ |
| 179 |
|
| 180 |
.. module:: django.contrib.messages.middleware |
| 181 |
:synopsis: Message middleware. |
| 182 |
|
| 183 |
.. class:: MessageMiddleware |
| 184 |
|
| 185 |
Enables cookie- and session-based message support. See the |
| 186 |
:doc:`messages documentation </ref/contrib/messages>`. |
| 187 |
|
| 188 |
.. _security-middleware: |
| 189 |
|
| 190 |
Security middleware |
| 191 |
------------------- |
| 192 |
|
| 193 |
.. module:: django.middleware.security |
| 194 |
:synopsis: Security middleware. |
| 195 |
|
| 196 |
.. warning:: |
| 197 |
If your deployment situation allows, it's usually a good idea to have your |
| 198 |
front-end web server perform the functionality provided by the |
| 199 |
``SecurityMiddleware``. That way, if there are requests that aren't served |
| 200 |
by Django (such as static media or user-uploaded files), they will have |
| 201 |
the same protections as requests to your Django application. |
| 202 |
|
| 203 |
.. class:: SecurityMiddleware |
| 204 |
|
| 205 |
The ``django.middleware.security.SecurityMiddleware`` provides several security |
| 206 |
enhancements to the request/response cycle. Each one can be independently |
| 207 |
enabled or disabled with a setting. |
| 208 |
|
| 209 |
* :setting:`SECURE_CONTENT_TYPE_NOSNIFF` |
| 210 |
* :setting:`SECURE_CROSS_ORIGIN_OPENER_POLICY` |
| 211 |
* :setting:`SECURE_HSTS_INCLUDE_SUBDOMAINS` |
| 212 |
* :setting:`SECURE_HSTS_PRELOAD` |
| 213 |
* :setting:`SECURE_HSTS_SECONDS` |
| 214 |
* :setting:`SECURE_REDIRECT_EXEMPT` |
| 215 |
* :setting:`SECURE_REFERRER_POLICY` |
| 216 |
* :setting:`SECURE_SSL_HOST` |
| 217 |
* :setting:`SECURE_SSL_REDIRECT` |
| 218 |
|
| 219 |
.. _http-strict-transport-security: |
| 220 |
|
| 221 |
HTTP Strict Transport Security |
| 222 |
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ |
| 223 |
|
| 224 |
For sites that should only be accessed over HTTPS, you can instruct modern |
| 225 |
browsers to refuse to connect to your domain name via an insecure connection |
| 226 |
(for a given period of time) by setting the `"Strict-Transport-Security" |
| 227 |
header`__. This reduces your exposure to some SSL-stripping man-in-the-middle |
| 228 |
(MITM) attacks. |
| 229 |
|
| 230 |
``SecurityMiddleware`` will set this header for you on all HTTPS responses if |
| 231 |
you set the :setting:`SECURE_HSTS_SECONDS` setting to a non-zero integer value. |
| 232 |
|
| 233 |
When enabling HSTS, it's a good idea to first use a small value for testing, |
| 234 |
for example, :setting:`SECURE_HSTS_SECONDS = 3600<SECURE_HSTS_SECONDS>` for one |
| 235 |
hour. Each time a web browser sees the HSTS header from your site, it will |
| 236 |
refuse to communicate non-securely (using HTTP) with your domain for the given |
| 237 |
period of time. Once you confirm that all assets are served securely on your |
| 238 |
site (i.e. HSTS didn't break anything), it's a good idea to increase this value |
| 239 |
so that infrequent visitors will be protected (31536000 seconds, i.e. 1 year, |
| 240 |
is common). |
| 241 |
|
| 242 |
Additionally, if you set the :setting:`SECURE_HSTS_INCLUDE_SUBDOMAINS` setting |
| 243 |
to ``True``, ``SecurityMiddleware`` will add the ``includeSubDomains`` directive |
| 244 |
to the ``Strict-Transport-Security`` header. This is recommended (assuming all |
| 245 |
subdomains are served exclusively using HTTPS), otherwise your site may still |
| 246 |
be vulnerable via an insecure connection to a subdomain. |
| 247 |
|
| 248 |
If you wish to submit your site to the `browser preload list`_, set the |
| 249 |
:setting:`SECURE_HSTS_PRELOAD` setting to ``True``. That appends the |
| 250 |
``preload`` directive to the ``Strict-Transport-Security`` header. |
| 251 |
|
| 252 |
.. warning:: |
| 253 |
The HSTS policy applies to your entire domain, not just the URL of the |
| 254 |
response that you set the header on. Therefore, you should only use it if |
| 255 |
your entire domain is served via HTTPS only. |
| 256 |
|
| 257 |
Browsers properly respecting the HSTS header will refuse to allow users to |
| 258 |
bypass warnings and connect to a site with an expired, self-signed, or |
| 259 |
otherwise invalid SSL certificate. If you use HSTS, make sure your |
| 260 |
certificates are in good shape and stay that way! |
| 261 |
|
| 262 |
.. note:: |
| 263 |
If you are deployed behind a load-balancer or reverse-proxy server, and the |
| 264 |
``Strict-Transport-Security`` header is not being added to your responses, |
| 265 |
it may be because Django doesn't realize that it's on a secure connection; |
| 266 |
you may need to set the :setting:`SECURE_PROXY_SSL_HEADER` setting. |
| 267 |
|
| 268 |
__ https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Strict-Transport-Security |
| 269 |
.. _browser preload list: https://hstspreload.org/ |
| 270 |
|
| 271 |
.. _referrer-policy: |
| 272 |
|
| 273 |
Referrer Policy |
| 274 |
~~~~~~~~~~~~~~~ |
| 275 |
|
| 276 |
Browsers use `the Referer header`__ as a way to send information to a site |
| 277 |
about how users got there. When a user clicks a link, the browser will send the |
| 278 |
full URL of the linking page as the referrer. While this can be useful for some |
| 279 |
purposes -- like figuring out who's linking to your site -- it also can cause |
| 280 |
privacy concerns by informing one site that a user was visiting another site. |
| 281 |
|
| 282 |
__ https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Referer |
| 283 |
|
| 284 |
Some browsers have the ability to accept hints about whether they should send |
| 285 |
the HTTP ``Referer`` header when a user clicks a link; this hint is provided |
| 286 |
via `the Referrer-Policy header`__. This header can suggest any of three |
| 287 |
behaviors to browsers: |
| 288 |
|
| 289 |
__ https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Referrer-Policy |
| 290 |
|
| 291 |
* Full URL: send the entire URL in the ``Referer`` header. For example, if the |
| 292 |
user is visiting ``https://example.com/page.html``, the ``Referer`` header |
| 293 |
would contain ``"https://example.com/page.html"``. |
| 294 |
|
| 295 |
* Origin only: send only the "origin" in the referrer. The origin consists of |
| 296 |
the scheme, host and (optionally) port number. For example, if the user is |
| 297 |
visiting ``https://example.com/page.html``, the origin would be |
| 298 |
``https://example.com/``. |
| 299 |
|
| 300 |
* No referrer: do not send a ``Referer`` header at all. |
| 301 |
|
| 302 |
There are two types of conditions this header can tell a browser to watch out |
| 303 |
for: |
| 304 |
|
| 305 |
* Same-origin versus cross-origin: a link from ``https://example.com/1.html`` |
| 306 |
to ``https://example.com/2.html`` is same-origin. A link from |
| 307 |
``https://example.com/page.html`` to ``https://not.example.com/page.html`` is |
| 308 |
cross-origin. |
| 309 |
|
| 310 |
* Protocol downgrade: a downgrade occurs if the page containing the link is |
| 311 |
served via HTTPS, but the page being linked to is not served via HTTPS. |
| 312 |
|
| 313 |
.. warning:: |
| 314 |
When your site is served via HTTPS, :ref:`Django's CSRF protection system |
| 315 |
<how-csrf-works>` requires the ``Referer`` header to be present, so |
| 316 |
completely disabling the ``Referer`` header will interfere with CSRF |
| 317 |
protection. To gain most of the benefits of disabling ``Referer`` headers |
| 318 |
while also keeping CSRF protection, consider enabling only same-origin |
| 319 |
referrers. |
| 320 |
|
| 321 |
``SecurityMiddleware`` can set the ``Referrer-Policy`` header for you, based on |
| 322 |
the :setting:`SECURE_REFERRER_POLICY` setting (note spelling: browsers send a |
| 323 |
``Referer`` header when a user clicks a link, but the header instructing a |
| 324 |
browser whether to do so is spelled ``Referrer-Policy``). The valid values for |
| 325 |
this setting are: |
| 326 |
|
| 327 |
``no-referrer`` |
| 328 |
Instructs the browser to send no referrer for links clicked on this site. |
| 329 |
|
| 330 |
``no-referrer-when-downgrade`` |
| 331 |
Instructs the browser to send a full URL as the referrer, but only when no |
| 332 |
protocol downgrade occurs. |
| 333 |
|
| 334 |
``origin`` |
| 335 |
Instructs the browser to send only the origin, not the full URL, as the |
| 336 |
referrer. |
| 337 |
|
| 338 |
``origin-when-cross-origin`` |
| 339 |
Instructs the browser to send the full URL as the referrer for same-origin |
| 340 |
links, and only the origin for cross-origin links. |
| 341 |
|
| 342 |
``same-origin`` |
| 343 |
Instructs the browser to send a full URL, but only for same-origin links. No |
| 344 |
referrer will be sent for cross-origin links. |
| 345 |
|
| 346 |
``strict-origin`` |
| 347 |
Instructs the browser to send only the origin, not the full URL, and to send |
| 348 |
no referrer when a protocol downgrade occurs. |
| 349 |
|
| 350 |
``strict-origin-when-cross-origin`` |
| 351 |
Instructs the browser to send the full URL when the link is same-origin and |
| 352 |
no protocol downgrade occurs; send only the origin when the link is |
| 353 |
cross-origin and no protocol downgrade occurs; and no referrer when a |
| 354 |
protocol downgrade occurs. |
| 355 |
|
| 356 |
``unsafe-url`` |
| 357 |
Instructs the browser to always send the full URL as the referrer. |
| 358 |
|
| 359 |
.. admonition:: Unknown Policy Values |
| 360 |
|
| 361 |
Where a policy value is `unknown`__ by a user agent, it is possible to |
| 362 |
specify multiple policy values to provide a fallback. The last specified |
| 363 |
value that is understood takes precedence. To support this, an iterable or |
| 364 |
comma-separated string can be used with :setting:`SECURE_REFERRER_POLICY`. |
| 365 |
|
| 366 |
__ https://w3c.github.io/webappsec-referrer-policy/#unknown-policy-values |
| 367 |
|
| 368 |
.. _cross-origin-opener-policy: |
| 369 |
|
| 370 |
Cross-Origin Opener Policy |
| 371 |
~~~~~~~~~~~~~~~~~~~~~~~~~~ |
| 372 |
|
| 373 |
Some browsers have the ability to isolate top-level windows from other |
| 374 |
documents by putting them in a separate browsing context group based on the |
| 375 |
value of the `Cross-Origin Opener Policy`__ (COOP) header. If a document that |
| 376 |
is isolated in this way opens a cross-origin popup window, the popup’s |
| 377 |
``window.opener`` property will be ``null``. Isolating windows using COOP is a |
| 378 |
defense-in-depth protection against cross-origin attacks, especially those like |
| 379 |
Spectre which allowed exfiltration of data loaded into a shared browsing |
| 380 |
context. |
| 381 |
|
| 382 |
__ https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cross-Origin-Opener-Policy |
| 383 |
|
| 384 |
``SecurityMiddleware`` can set the ``Cross-Origin-Opener-Policy`` header for |
| 385 |
you, based on the :setting:`SECURE_CROSS_ORIGIN_OPENER_POLICY` setting. The |
| 386 |
valid values for this setting are: |
| 387 |
|
| 388 |
``same-origin`` |
| 389 |
Isolates the browsing context exclusively to same-origin documents. |
| 390 |
Cross-origin documents are not loaded in the same browsing context. This |
| 391 |
is the default and most secure option. |
| 392 |
|
| 393 |
``same-origin-allow-popups`` |
| 394 |
Isolates the browsing context to same-origin documents or those which |
| 395 |
either don't set COOP or which opt out of isolation by setting a COOP of |
| 396 |
``unsafe-none``. |
| 397 |
|
| 398 |
``unsafe-none`` |
| 399 |
Allows the document to be added to its opener's browsing context group |
| 400 |
unless the opener itself has a COOP of ``same-origin`` or |
| 401 |
``same-origin-allow-popups``. |
| 402 |
|
| 403 |
.. _x-content-type-options: |
| 404 |
|
| 405 |
``X-Content-Type-Options: nosniff`` |
| 406 |
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ |
| 407 |
|
| 408 |
Some browsers will try to guess the content types of the assets that they |
| 409 |
fetch, overriding the ``Content-Type`` header. While this can help display |
| 410 |
sites with improperly configured servers, it can also pose a security |
| 411 |
risk. |
| 412 |
|
| 413 |
If your site serves user-uploaded files, a malicious user could upload a |
| 414 |
specially-crafted file that would be interpreted as HTML or JavaScript by |
| 415 |
the browser when you expected it to be something harmless. |
| 416 |
|
| 417 |
To prevent the browser from guessing the content type and force it to |
| 418 |
always use the type provided in the ``Content-Type`` header, you can pass |
| 419 |
the `X-Content-Type-Options: nosniff`__ header. ``SecurityMiddleware`` will |
| 420 |
do this for all responses if the :setting:`SECURE_CONTENT_TYPE_NOSNIFF` setting |
| 421 |
is ``True``. |
| 422 |
|
| 423 |
Note that in most deployment situations where Django isn't involved in serving |
| 424 |
user-uploaded files, this setting won't help you. For example, if your |
| 425 |
:setting:`MEDIA_URL` is served directly by your front-end web server (nginx, |
| 426 |
Apache, etc.) then you'd want to set this header there. On the other hand, if |
| 427 |
you are using Django to do something like require authorization in order to |
| 428 |
download files and you cannot set the header using your web server, this |
| 429 |
setting will be useful. |
| 430 |
|
| 431 |
__ https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-Content-Type-Options |
| 432 |
|
| 433 |
.. _ssl-redirect: |
| 434 |
|
| 435 |
SSL Redirect |
| 436 |
~~~~~~~~~~~~ |
| 437 |
|
| 438 |
If your site offers both HTTP and HTTPS connections, most users will end up |
| 439 |
with an unsecured connection by default. For best security, you should redirect |
| 440 |
all HTTP connections to HTTPS. |
| 441 |
|
| 442 |
If you set the :setting:`SECURE_SSL_REDIRECT` setting to True, |
| 443 |
``SecurityMiddleware`` will permanently (HTTP 301) redirect all HTTP |
| 444 |
connections to HTTPS. |
| 445 |
|
| 446 |
.. note:: |
| 447 |
|
| 448 |
For performance reasons, it's preferable to do these redirects outside of |
| 449 |
Django, in a front-end load balancer or reverse-proxy server such as |
| 450 |
`nginx`_. :setting:`SECURE_SSL_REDIRECT` is intended for the deployment |
| 451 |
situations where this isn't an option. |
| 452 |
|
| 453 |
If the :setting:`SECURE_SSL_HOST` setting has a value, all redirects will be |
| 454 |
sent to that host instead of the originally-requested host. |
| 455 |
|
| 456 |
If there are a few pages on your site that should be available over HTTP, and |
| 457 |
not redirected to HTTPS, you can list regular expressions to match those URLs |
| 458 |
in the :setting:`SECURE_REDIRECT_EXEMPT` setting. |
| 459 |
|
| 460 |
.. note:: |
| 461 |
If you are deployed behind a load-balancer or reverse-proxy server and |
| 462 |
Django can't seem to tell when a request actually is already secure, you |
| 463 |
may need to set the :setting:`SECURE_PROXY_SSL_HEADER` setting. |
| 464 |
|
| 465 |
.. _nginx: https://nginx.org/ |
| 466 |
|
| 467 |
Session middleware |
| 468 |
------------------ |
| 469 |
|
| 470 |
.. module:: django.contrib.sessions.middleware |
| 471 |
:synopsis: Session middleware. |
| 472 |
|
| 473 |
.. class:: SessionMiddleware |
| 474 |
|
| 475 |
Enables session support. See the :doc:`session documentation |
| 476 |
</topics/http/sessions>`. |
| 477 |
|
| 478 |
Site middleware |
| 479 |
--------------- |
| 480 |
|
| 481 |
.. module:: django.contrib.sites.middleware |
| 482 |
:synopsis: Site middleware. |
| 483 |
|
| 484 |
.. class:: CurrentSiteMiddleware |
| 485 |
|
| 486 |
Adds the ``site`` attribute representing the current site to every incoming |
| 487 |
``HttpRequest`` object. See the :ref:`sites documentation <site-middleware>`. |
| 488 |
|
| 489 |
Authentication middleware |
| 490 |
------------------------- |
| 491 |
|
| 492 |
.. module:: django.contrib.auth.middleware |
| 493 |
:synopsis: Authentication middleware. |
| 494 |
|
| 495 |
.. class:: AuthenticationMiddleware |
| 496 |
|
| 497 |
Adds the ``user`` attribute, representing the currently-logged-in user, to |
| 498 |
every incoming ``HttpRequest`` object. See :ref:`Authentication in web requests |
| 499 |
<auth-web-requests>`. |
| 500 |
|
| 501 |
.. class:: LoginRequiredMiddleware |
| 502 |
|
| 503 |
Subclass the middleware and override the following attributes and methods |
| 504 |
to customize behavior for unauthenticated requests. |
| 505 |
|
| 506 |
.. attribute:: redirect_field_name |
| 507 |
|
| 508 |
Defaults to ``"next"``. |
| 509 |
|
| 510 |
.. method:: get_login_url() |
| 511 |
|
| 512 |
Returns the URL that unauthenticated requests will be redirected to. This |
| 513 |
result is either the ``login_url`` set on the |
| 514 |
:func:`~django.contrib.auth.decorators.login_required` decorator (if not |
| 515 |
``None``), or :setting:`settings.LOGIN_URL <LOGIN_URL>`. |
| 516 |
|
| 517 |
.. method:: get_redirect_field_name() |
| 518 |
|
| 519 |
Returns the name of the query parameter that contains the URL the user |
| 520 |
should be redirected to after a successful login. This result is either |
| 521 |
the ``redirect_field_name`` set on the |
| 522 |
:func:`~.django.contrib.auth.decorators.login_required` decorator (if not |
| 523 |
``None``), or :attr:`redirect_field_name`. If ``None`` is returned, a query |
| 524 |
parameter won't be added. |
| 525 |
|
| 526 |
.. versionadded:: 5.1 |
| 527 |
|
| 528 |
Redirects all unauthenticated requests to a login page, except for views |
| 529 |
excluded with :func:`~.django.contrib.auth.decorators.login_not_required`. The |
| 530 |
login page defaults to :setting:`settings.LOGIN_URL <LOGIN_URL>`, but can be |
| 531 |
customized. |
| 532 |
|
| 533 |
Enable this middleware by adding it to the :setting:`MIDDLEWARE` setting |
| 534 |
**after** :class:`~django.contrib.auth.middleware.AuthenticationMiddleware`:: |
| 535 |
|
| 536 |
MIDDLEWARE = [ |
| 537 |
"...", |
| 538 |
"django.contrib.auth.middleware.AuthenticationMiddleware", |
| 539 |
"django.contrib.auth.middleware.LoginRequiredMiddleware", |
| 540 |
"...", |
| 541 |
] |
| 542 |
|
| 543 |
Make a view public, allowing unauthenticated requests, with |
| 544 |
:func:`~.django.contrib.auth.decorators.login_not_required`. For example:: |
| 545 |
|
| 546 |
from django.contrib.auth.decorators import login_not_required |
| 547 |
|
| 548 |
|
| 549 |
@login_not_required |
| 550 |
def contact_us(request): ... |
| 551 |
|
| 552 |
Customize the login URL or field name for authenticated views with the |
| 553 |
:func:`~.django.contrib.auth.decorators.login_required` decorator to set |
| 554 |
``login_url`` or ``redirect_field_name`` respectively. For example:: |
| 555 |
|
| 556 |
from django.contrib.auth.decorators import login_required |
| 557 |
from django.utils.decorators import method_decorator |
| 558 |
from django.views.generic import View |
| 559 |
|
| 560 |
|
| 561 |
@login_required(login_url="/books/login/", redirect_field_name="redirect_to") |
| 562 |
def book_dashboard(request): ... |
| 563 |
|
| 564 |
|
| 565 |
@method_decorator( |
| 566 |
login_required(login_url="/books/login/", redirect_field_name="redirect_to"), |
| 567 |
name="dispatch", |
| 568 |
) |
| 569 |
class BookMetrics(View): |
| 570 |
pass |
| 571 |
|
| 572 |
.. admonition:: Ensure that your login view does not require a login. |
| 573 |
|
| 574 |
To prevent infinite redirects, ensure you have |
| 575 |
:ref:`enabled unauthenticated requests |
| 576 |
<disable-login-required-middleware-for-views>` to your login view. |
| 577 |
|
| 578 |
.. class:: RemoteUserMiddleware |
| 579 |
|
| 580 |
Middleware for utilizing web server provided authentication. See |
| 581 |
:doc:`/howto/auth-remote-user` for usage details. |
| 582 |
|
| 583 |
.. class:: PersistentRemoteUserMiddleware |
| 584 |
|
| 585 |
Middleware for utilizing web server provided authentication when enabled only |
| 586 |
on the login page. See :ref:`persistent-remote-user-middleware-howto` for usage |
| 587 |
details. |
| 588 |
|
| 589 |
CSRF protection middleware |
| 590 |
-------------------------- |
| 591 |
|
| 592 |
.. currentmodule:: django.middleware.csrf |
| 593 |
|
| 594 |
.. class:: CsrfViewMiddleware |
| 595 |
|
| 596 |
Adds protection against Cross Site Request Forgeries by adding hidden form |
| 597 |
fields to POST forms and checking requests for the correct value. See the |
| 598 |
:doc:`Cross Site Request Forgery protection documentation </ref/csrf>`. |
| 599 |
|
| 600 |
You can add Cross Site Request Forgery protection to individual views using the |
| 601 |
:func:`~django.views.decorators.csrf.csrf_protect()` decorator. |
| 602 |
|
| 603 |
``X-Frame-Options`` middleware |
| 604 |
------------------------------ |
| 605 |
|
| 606 |
.. currentmodule:: django.middleware.clickjacking |
| 607 |
|
| 608 |
.. class:: XFrameOptionsMiddleware |
| 609 |
|
| 610 |
Simple :doc:`clickjacking protection via the X-Frame-Options header </ref/clickjacking/>`. |
| 611 |
|
| 612 |
.. _middleware-ordering: |
| 613 |
|
| 614 |
Middleware ordering |
| 615 |
=================== |
| 616 |
|
| 617 |
Here are some hints about the ordering of various Django middleware classes: |
| 618 |
|
| 619 |
#. :class:`~django.middleware.security.SecurityMiddleware` |
| 620 |
|
| 621 |
It should go near the top of the list if you're going to turn on the SSL |
| 622 |
redirect as that avoids running through a bunch of other unnecessary |
| 623 |
middleware. |
| 624 |
|
| 625 |
#. :class:`~django.middleware.cache.UpdateCacheMiddleware` |
| 626 |
|
| 627 |
Before those that modify the ``Vary`` header (``SessionMiddleware``, |
| 628 |
``GZipMiddleware``, ``LocaleMiddleware``). |
| 629 |
|
| 630 |
#. :class:`~django.middleware.gzip.GZipMiddleware` |
| 631 |
|
| 632 |
Before any middleware that may change or use the response body. |
| 633 |
|
| 634 |
After ``UpdateCacheMiddleware``: Modifies ``Vary`` header. |
| 635 |
|
| 636 |
#. :class:`~django.contrib.sessions.middleware.SessionMiddleware` |
| 637 |
|
| 638 |
Before any middleware that may raise an exception to trigger an error |
| 639 |
view (such as :exc:`~django.core.exceptions.PermissionDenied`) if you're |
| 640 |
using :setting:`CSRF_USE_SESSIONS`. |
| 641 |
|
| 642 |
After ``UpdateCacheMiddleware``: Modifies ``Vary`` header. |
| 643 |
|
| 644 |
#. :class:`~django.middleware.http.ConditionalGetMiddleware` |
| 645 |
|
| 646 |
Before any middleware that may change the response (it sets the ``ETag`` |
| 647 |
header). |
| 648 |
|
| 649 |
After ``GZipMiddleware`` so it won't calculate an ``ETag`` header on gzipped |
| 650 |
contents. |
| 651 |
|
| 652 |
#. :class:`~django.middleware.locale.LocaleMiddleware` |
| 653 |
|
| 654 |
One of the topmost, after ``SessionMiddleware`` (uses session data) and |
| 655 |
``UpdateCacheMiddleware`` (modifies ``Vary`` header). |
| 656 |
|
| 657 |
#. :class:`~django.middleware.common.CommonMiddleware` |
| 658 |
|
| 659 |
Before any middleware that may change the response (it sets the |
| 660 |
``Content-Length`` header). A middleware that appears before |
| 661 |
``CommonMiddleware`` and changes the response must reset ``Content-Length``. |
| 662 |
|
| 663 |
Close to the top: it redirects when :setting:`APPEND_SLASH` or |
| 664 |
:setting:`PREPEND_WWW` are set to ``True``. |
| 665 |
|
| 666 |
After ``SessionMiddleware`` if you're using :setting:`CSRF_USE_SESSIONS`. |
| 667 |
|
| 668 |
#. :class:`~django.middleware.csrf.CsrfViewMiddleware` |
| 669 |
|
| 670 |
Before any view middleware that assumes that CSRF attacks have been dealt |
| 671 |
with. |
| 672 |
|
| 673 |
Before :class:`~django.contrib.auth.middleware.RemoteUserMiddleware`, or any |
| 674 |
other authentication middleware that may perform a login, and hence rotate |
| 675 |
the CSRF token, before calling down the middleware chain. |
| 676 |
|
| 677 |
After ``SessionMiddleware`` if you're using :setting:`CSRF_USE_SESSIONS`. |
| 678 |
|
| 679 |
#. :class:`~django.contrib.auth.middleware.AuthenticationMiddleware` |
| 680 |
|
| 681 |
After ``SessionMiddleware``: uses session storage. |
| 682 |
|
| 683 |
#. :class:`~django.contrib.auth.middleware.LoginRequiredMiddleware` |
| 684 |
|
| 685 |
.. versionadded:: 5.1 |
| 686 |
|
| 687 |
After ``AuthenticationMiddleware``: uses user object. |
| 688 |
|
| 689 |
#. :class:`~django.contrib.messages.middleware.MessageMiddleware` |
| 690 |
|
| 691 |
After ``SessionMiddleware``: can use session-based storage. |
| 692 |
|
| 693 |
#. :class:`~django.middleware.cache.FetchFromCacheMiddleware` |
| 694 |
|
| 695 |
After any middleware that modifies the ``Vary`` header: that header is used |
| 696 |
to pick a value for the cache hash-key. |
| 697 |
|
| 698 |
#. :class:`~django.contrib.flatpages.middleware.FlatpageFallbackMiddleware` |
| 699 |
|
| 700 |
Should be near the bottom as it's a last-resort type of middleware. |
| 701 |
|
| 702 |
#. :class:`~django.contrib.redirects.middleware.RedirectFallbackMiddleware` |
| 703 |
|
| 704 |
Should be near the bottom as it's a last-resort type of middleware. |