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