middleware.txt 17 KB

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