middleware.txt 26 KB

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