middleware.txt 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532
  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. Adds a few conveniences for perfectionists:
  26. * Forbids access to user agents in the :setting:`DISALLOWED_USER_AGENTS`
  27. setting, which should be a list of compiled regular expression objects.
  28. * Performs URL rewriting based on the :setting:`APPEND_SLASH` and
  29. :setting:`PREPEND_WWW` settings.
  30. If :setting:`APPEND_SLASH` is ``True`` and the initial URL doesn't end
  31. with a slash, and it is not found in the URLconf, then a new URL is
  32. formed by appending a slash at the end. If this new URL is found in the
  33. URLconf, then Django redirects the request to this new URL. Otherwise,
  34. the initial URL is processed as usual.
  35. For example, ``foo.com/bar`` will be redirected to ``foo.com/bar/`` if
  36. you don't have a valid URL pattern for ``foo.com/bar`` but *do* have a
  37. valid pattern for ``foo.com/bar/``.
  38. If :setting:`PREPEND_WWW` is ``True``, URLs that lack a leading "www."
  39. will be redirected to the same URL with a leading "www."
  40. Both of these options are meant to normalize URLs. The philosophy is that
  41. each URL should exist in one, and only one, place. Technically a URL
  42. ``foo.com/bar`` is distinct from ``foo.com/bar/`` -- a search-engine
  43. indexer would treat them as separate URLs -- so it's best practice to
  44. normalize URLs.
  45. * Handles ETags based on the :setting:`USE_ETAGS` setting. If
  46. :setting:`USE_ETAGS` is set to ``True``, Django will calculate an ETag
  47. for each request by MD5-hashing the page content, and it'll take care of
  48. sending ``Not Modified`` responses, if appropriate.
  49. * Sets the ``Content-Length`` header for non-streaming responses.
  50. .. versionchanged: 1.11
  51. Older versions didn't set the ``Content-Length`` header.
  52. .. deprecated:: 1.11
  53. The :setting:`USE_ETAGS` setting is deprecated in favor of using
  54. :class:`~django.middleware.http.ConditionalGetMiddleware` for ETag
  55. processing.
  56. .. attribute:: CommonMiddleware.response_redirect_class
  57. Defaults to :class:`~django.http.HttpResponsePermanentRedirect`. Subclass
  58. ``CommonMiddleware`` and override the attribute to customize the redirects
  59. issued by the middleware.
  60. .. class:: BrokenLinkEmailsMiddleware
  61. * Sends broken link notification emails to :setting:`MANAGERS` (see
  62. :doc:`/howto/error-reporting`).
  63. Exception middleware
  64. --------------------
  65. .. module:: django.middleware.exception
  66. :synopsis: Middleware to return responses for exceptions.
  67. .. class:: ExceptionMiddleware
  68. .. versionadded:: 1.10
  69. Catches exceptions raised during the request/response cycle and returns the
  70. appropriate response.
  71. * :class:`~django.http.Http404` is processed by
  72. :data:`~django.conf.urls.handler404` (or a more friendly debug page if
  73. :setting:`DEBUG=True <DEBUG>`).
  74. * :class:`~django.core.exceptions.PermissionDenied` is processed
  75. by :data:`~django.conf.urls.handler403`.
  76. * ``MultiPartParserError`` is processed by :data:`~django.conf.urls.handler400`.
  77. * :class:`~django.core.exceptions.SuspiciousOperation` is processed by
  78. :data:`~django.conf.urls.handler400` (or a more friendly debug page if
  79. :setting:`DEBUG=True <DEBUG>`).
  80. * Any other exception is processed by :data:`~django.conf.urls.handler500`
  81. (or a more friendly debug page if :setting:`DEBUG=True <DEBUG>`).
  82. Django uses this middleware regardless of whether or not you include it in
  83. :setting:`MIDDLEWARE`, however, you may want to subclass if your own middleware
  84. needs to transform any of these exceptions into the appropriate responses.
  85. :class:`~django.middleware.locale.LocaleMiddleware` does this, for example.
  86. GZip middleware
  87. ---------------
  88. .. module:: django.middleware.gzip
  89. :synopsis: Middleware to serve GZipped content for performance.
  90. .. class:: GZipMiddleware
  91. .. warning::
  92. Security researchers recently revealed that when compression techniques
  93. (including ``GZipMiddleware``) are used on a website, the site may become
  94. exposed to a number of possible attacks. Before using ``GZipMiddleware`` on
  95. your site, you should consider very carefully whether you are subject to
  96. these attacks. If you're in *any* doubt about whether you're affected, you
  97. should avoid using ``GZipMiddleware``. For more details, see the `the BREACH
  98. paper (PDF)`_ and `breachattack.com`_.
  99. .. _the BREACH paper (PDF): http://breachattack.com/resources/BREACH%20-%20SSL,%20gone%20in%2030%20seconds.pdf
  100. .. _breachattack.com: http://breachattack.com
  101. Compresses content for browsers that understand GZip compression (all modern
  102. browsers).
  103. This middleware should be placed before any other middleware that need to
  104. read or write the response body so that compression happens afterward.
  105. It will NOT compress content if any of the following are true:
  106. * The content body is less than 200 bytes long.
  107. * The response has already set the ``Content-Encoding`` header.
  108. * The request (the browser) hasn't sent an ``Accept-Encoding`` header
  109. containing ``gzip``.
  110. You can apply GZip compression to individual views using the
  111. :func:`~django.views.decorators.gzip.gzip_page()` decorator.
  112. .. versionchanged:: 1.10
  113. In older versions, Django's CSRF protection mechanism was vulnerable to
  114. BREACH attacks when compression was used. This is no longer the case, but
  115. you should still take care not to compromise your own secrets this way.
  116. Conditional GET middleware
  117. --------------------------
  118. .. module:: django.middleware.http
  119. :synopsis: Middleware handling advanced HTTP features.
  120. .. class:: ConditionalGetMiddleware
  121. Handles conditional GET operations. If the response doesn't have an ``ETag``
  122. header, the middleware adds one if needed. If the response has a ``ETag`` or
  123. ``Last-Modified`` header, and the request has ``If-None-Match`` or
  124. ``If-Modified-Since``, the response is replaced by an
  125. :class:`~django.http.HttpResponseNotModified`.
  126. Also sets the ``Date`` and ``Content-Length`` response-headers.
  127. .. versionchanged:: 1.11
  128. In older versions, the middleware didn't set the ``ETag`` header.
  129. Locale middleware
  130. -----------------
  131. .. module:: django.middleware.locale
  132. :synopsis: Middleware to enable language selection based on the request.
  133. .. class:: LocaleMiddleware
  134. Enables language selection based on data from the request. It customizes
  135. content for each user. See the :doc:`internationalization documentation
  136. </topics/i18n/translation>`.
  137. .. attribute:: LocaleMiddleware.response_redirect_class
  138. Defaults to :class:`~django.http.HttpResponseRedirect`. Subclass
  139. ``LocaleMiddleware`` and override the attribute to customize the redirects
  140. issued by the middleware.
  141. Message middleware
  142. ------------------
  143. .. module:: django.contrib.messages.middleware
  144. :synopsis: Message middleware.
  145. .. class:: MessageMiddleware
  146. Enables cookie- and session-based message support. See the
  147. :doc:`messages documentation </ref/contrib/messages>`.
  148. .. _security-middleware:
  149. Security middleware
  150. -------------------
  151. .. module:: django.middleware.security
  152. :synopsis: Security middleware.
  153. .. warning::
  154. If your deployment situation allows, it's usually a good idea to have your
  155. front-end Web server perform the functionality provided by the
  156. ``SecurityMiddleware``. That way, if there are requests that aren't served
  157. by Django (such as static media or user-uploaded files), they will have
  158. the same protections as requests to your Django application.
  159. .. class:: SecurityMiddleware
  160. The ``django.middleware.security.SecurityMiddleware`` provides several security
  161. enhancements to the request/response cycle. Each one can be independently
  162. enabled or disabled with a setting.
  163. * :setting:`SECURE_BROWSER_XSS_FILTER`
  164. * :setting:`SECURE_CONTENT_TYPE_NOSNIFF`
  165. * :setting:`SECURE_HSTS_INCLUDE_SUBDOMAINS`
  166. * :setting:`SECURE_HSTS_PRELOAD`
  167. * :setting:`SECURE_HSTS_SECONDS`
  168. * :setting:`SECURE_REDIRECT_EXEMPT`
  169. * :setting:`SECURE_SSL_HOST`
  170. * :setting:`SECURE_SSL_REDIRECT`
  171. .. _http-strict-transport-security:
  172. HTTP Strict Transport Security
  173. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  174. For sites that should only be accessed over HTTPS, you can instruct modern
  175. browsers to refuse to connect to your domain name via an insecure connection
  176. (for a given period of time) by setting the `"Strict-Transport-Security"
  177. header`_. This reduces your exposure to some SSL-stripping man-in-the-middle
  178. (MITM) attacks.
  179. ``SecurityMiddleware`` will set this header for you on all HTTPS responses if
  180. you set the :setting:`SECURE_HSTS_SECONDS` setting to a non-zero integer value.
  181. When enabling HSTS, it's a good idea to first use a small value for testing,
  182. for example, :setting:`SECURE_HSTS_SECONDS = 3600<SECURE_HSTS_SECONDS>` for one
  183. hour. Each time a Web browser sees the HSTS header from your site, it will
  184. refuse to communicate non-securely (using HTTP) with your domain for the given
  185. period of time. Once you confirm that all assets are served securely on your
  186. site (i.e. HSTS didn't break anything), it's a good idea to increase this value
  187. so that infrequent visitors will be protected (31536000 seconds, i.e. 1 year,
  188. is common).
  189. Additionally, if you set the :setting:`SECURE_HSTS_INCLUDE_SUBDOMAINS` setting
  190. to ``True``, ``SecurityMiddleware`` will add the ``includeSubDomains`` directive
  191. to the ``Strict-Transport-Security`` header. This is recommended (assuming all
  192. subdomains are served exclusively using HTTPS), otherwise your site may still
  193. be vulnerable via an insecure connection to a subdomain.
  194. If you wish to submit your site to the `browser preload list`_, set the
  195. :setting:`SECURE_HSTS_PRELOAD` setting to ``True``. That appends the
  196. ``preload`` directive to the ``Strict-Transport-Security`` header.
  197. .. warning::
  198. The HSTS policy applies to your entire domain, not just the URL of the
  199. response that you set the header on. Therefore, you should only use it if
  200. your entire domain is served via HTTPS only.
  201. Browsers properly respecting the HSTS header will refuse to allow users to
  202. bypass warnings and connect to a site with an expired, self-signed, or
  203. otherwise invalid SSL certificate. If you use HSTS, make sure your
  204. certificates are in good shape and stay that way!
  205. .. note::
  206. If you are deployed behind a load-balancer or reverse-proxy server, and the
  207. ``Strict-Transport-Security`` header is not being added to your responses,
  208. it may be because Django doesn't realize that it's on a secure connection;
  209. you may need to set the :setting:`SECURE_PROXY_SSL_HEADER` setting.
  210. .. _"Strict-Transport-Security" header: https://en.wikipedia.org/wiki/Strict_Transport_Security
  211. .. _browser preload list: https://hstspreload.appspot.com/
  212. .. _x-content-type-options:
  213. ``X-Content-Type-Options: nosniff``
  214. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  215. Some browsers will try to guess the content types of the assets that they
  216. fetch, overriding the ``Content-Type`` header. While this can help display
  217. sites with improperly configured servers, it can also pose a security
  218. risk.
  219. If your site serves user-uploaded files, a malicious user could upload a
  220. specially-crafted file that would be interpreted as HTML or JavaScript by
  221. the browser when you expected it to be something harmless.
  222. To learn more about this header and how the browser treats it, you can
  223. read about it on the `IE Security Blog`_.
  224. To prevent the browser from guessing the content type and force it to
  225. always use the type provided in the ``Content-Type`` header, you can pass
  226. the ``X-Content-Type-Options: nosniff`` header. ``SecurityMiddleware`` will
  227. do this for all responses if the :setting:`SECURE_CONTENT_TYPE_NOSNIFF` setting
  228. is ``True``.
  229. Note that in most deployment situations where Django isn't involved in serving
  230. user-uploaded files, this setting won't help you. For example, if your
  231. :setting:`MEDIA_URL` is served directly by your front-end Web server (nginx,
  232. Apache, etc.) then you'd want to set this header there. On the other hand, if
  233. you are using Django to do something like require authorization in order to
  234. download files and you cannot set the header using your Web server, this
  235. setting will be useful.
  236. .. _IE Security Blog: http://blogs.msdn.com/b/ie/archive/2008/09/02/ie8-security-part-vi-beta-2-update.aspx
  237. .. _x-xss-protection:
  238. ``X-XSS-Protection: 1; mode=block``
  239. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  240. Some browsers have the ability to block content that appears to be an `XSS
  241. attack`_. They work by looking for JavaScript content in the GET or POST
  242. parameters of a page. If the JavaScript is replayed in the server's response,
  243. the page is blocked from rendering and an error page is shown instead.
  244. The `X-XSS-Protection header`_ is used to control the operation of the
  245. XSS filter.
  246. To enable the XSS filter in the browser, and force it to always block
  247. suspected XSS attacks, you can pass the ``X-XSS-Protection: 1; mode=block``
  248. header. ``SecurityMiddleware`` will do this for all responses if the
  249. :setting:`SECURE_BROWSER_XSS_FILTER` setting is ``True``.
  250. .. warning::
  251. The browser XSS filter is a useful defense measure, but must not be
  252. relied upon exclusively. It cannot detect all XSS attacks and not all
  253. browsers support the header. Ensure you are still :ref:`validating and
  254. sanitizing <cross-site-scripting>` all input to prevent XSS attacks.
  255. .. _XSS attack: https://en.wikipedia.org/wiki/Cross-site_scripting
  256. .. _X-XSS-Protection header: http://blogs.msdn.com/b/ie/archive/2008/07/02/ie8-security-part-iv-the-xss-filter.aspx
  257. .. _ssl-redirect:
  258. SSL Redirect
  259. ~~~~~~~~~~~~
  260. If your site offers both HTTP and HTTPS connections, most users will end up
  261. with an unsecured connection by default. For best security, you should redirect
  262. all HTTP connections to HTTPS.
  263. If you set the :setting:`SECURE_SSL_REDIRECT` setting to True,
  264. ``SecurityMiddleware`` will permanently (HTTP 301) redirect all HTTP
  265. connections to HTTPS.
  266. .. note::
  267. For performance reasons, it's preferable to do these redirects outside of
  268. Django, in a front-end load balancer or reverse-proxy server such as
  269. `nginx`_. :setting:`SECURE_SSL_REDIRECT` is intended for the deployment
  270. situations where this isn't an option.
  271. If the :setting:`SECURE_SSL_HOST` setting has a value, all redirects will be
  272. sent to that host instead of the originally-requested host.
  273. If there are a few pages on your site that should be available over HTTP, and
  274. not redirected to HTTPS, you can list regular expressions to match those URLs
  275. in the :setting:`SECURE_REDIRECT_EXEMPT` setting.
  276. .. note::
  277. If you are deployed behind a load-balancer or reverse-proxy server and
  278. Django can't seem to tell when a request actually is already secure, you
  279. may need to set the :setting:`SECURE_PROXY_SSL_HEADER` setting.
  280. .. _nginx: http://nginx.org
  281. Session middleware
  282. ------------------
  283. .. module:: django.contrib.sessions.middleware
  284. :synopsis: Session middleware.
  285. .. class:: SessionMiddleware
  286. Enables session support. See the :doc:`session documentation
  287. </topics/http/sessions>`.
  288. Site middleware
  289. ---------------
  290. .. module:: django.contrib.sites.middleware
  291. :synopsis: Site middleware.
  292. .. class:: CurrentSiteMiddleware
  293. Adds the ``site`` attribute representing the current site to every incoming
  294. ``HttpRequest`` object. See the :ref:`sites documentation <site-middleware>`.
  295. Authentication middleware
  296. -------------------------
  297. .. module:: django.contrib.auth.middleware
  298. :synopsis: Authentication middleware.
  299. .. class:: AuthenticationMiddleware
  300. Adds the ``user`` attribute, representing the currently-logged-in user, to
  301. every incoming ``HttpRequest`` object. See :ref:`Authentication in Web requests
  302. <auth-web-requests>`.
  303. .. class:: RemoteUserMiddleware
  304. Middleware for utilizing Web server provided authentication. See
  305. :doc:`/howto/auth-remote-user` for usage details.
  306. .. class:: PersistentRemoteUserMiddleware
  307. Middleware for utilizing Web server provided authentication when enabled only
  308. on the login page. See :ref:`persistent-remote-user-middleware-howto` for usage
  309. details.
  310. CSRF protection middleware
  311. --------------------------
  312. .. module:: django.middleware.csrf
  313. :synopsis: Middleware adding protection against Cross Site Request
  314. Forgeries.
  315. .. class:: CsrfViewMiddleware
  316. Adds protection against Cross Site Request Forgeries by adding hidden form
  317. fields to POST forms and checking requests for the correct value. See the
  318. :doc:`Cross Site Request Forgery protection documentation </ref/csrf>`.
  319. ``X-Frame-Options`` middleware
  320. ------------------------------
  321. .. module:: django.middleware.clickjacking
  322. :synopsis: Clickjacking protection
  323. .. class:: XFrameOptionsMiddleware
  324. Simple :doc:`clickjacking protection via the X-Frame-Options header </ref/clickjacking/>`.
  325. .. _middleware-ordering:
  326. Middleware ordering
  327. ===================
  328. Here are some hints about the ordering of various Django middleware classes:
  329. #. :class:`~django.middleware.security.SecurityMiddleware`
  330. It should go near the top of the list if you're going to turn on the SSL
  331. redirect as that avoids running through a bunch of other unnecessary
  332. middleware.
  333. #. :class:`~django.middleware.cache.UpdateCacheMiddleware`
  334. Before those that modify the ``Vary`` header (``SessionMiddleware``,
  335. ``GZipMiddleware``, ``LocaleMiddleware``).
  336. #. :class:`~django.middleware.gzip.GZipMiddleware`
  337. Before any middleware that may change or use the response body.
  338. After ``UpdateCacheMiddleware``: Modifies ``Vary`` header.
  339. #. :class:`~django.middleware.http.ConditionalGetMiddleware`
  340. Before ``CommonMiddleware``: uses its ``ETag`` header when
  341. :setting:`USE_ETAGS` = ``True``.
  342. #. :class:`~django.contrib.sessions.middleware.SessionMiddleware`
  343. After ``UpdateCacheMiddleware``: Modifies ``Vary`` header.
  344. #. :class:`~django.middleware.locale.LocaleMiddleware`
  345. One of the topmost, after ``SessionMiddleware`` (uses session data) and
  346. ``UpdateCacheMiddleware`` (modifies ``Vary`` header).
  347. #. :class:`~django.middleware.common.CommonMiddleware`
  348. Before any middleware that may change the response (it calculates ``ETags``).
  349. After ``GZipMiddleware`` so it won't calculate an ``ETag`` header on gzipped
  350. contents.
  351. Close to the top: it redirects when :setting:`APPEND_SLASH` or
  352. :setting:`PREPEND_WWW` are set to ``True``.
  353. #. :class:`~django.middleware.csrf.CsrfViewMiddleware`
  354. Before any view middleware that assumes that CSRF attacks have been dealt
  355. with.
  356. #. :class:`~django.contrib.auth.middleware.AuthenticationMiddleware`
  357. After ``SessionMiddleware``: uses session storage.
  358. #. :class:`~django.contrib.messages.middleware.MessageMiddleware`
  359. After ``SessionMiddleware``: can use session-based storage.
  360. #. :class:`~django.middleware.cache.FetchFromCacheMiddleware`
  361. After any middleware that modifies the ``Vary`` header: that header is used
  362. to pick a value for the cache hash-key.
  363. #. :class:`~django.contrib.flatpages.middleware.FlatpageFallbackMiddleware`
  364. Should be near the bottom as it's a last-resort type of middleware.
  365. #. :class:`~django.contrib.redirects.middleware.RedirectFallbackMiddleware`
  366. Should be near the bottom as it's a last-resort type of middleware.