DESCRIPTION.rst 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511
  1. django-cors-headers
  2. ===================
  3. A Django App that adds CORS (Cross-Origin Resource Sharing) headers to
  4. responses.
  5. Although JSON-P is useful, it is strictly limited to GET requests. CORS
  6. builds on top of ``XmlHttpRequest`` to allow developers to make cross-domain
  7. requests, similar to same-domain requests. Read more about it here:
  8. http://www.html5rocks.com/en/tutorials/cors/
  9. .. image:: https://travis-ci.org/ottoyiu/django-cors-headers.svg?branch=master
  10. :target: https://travis-ci.org/ottoyiu/django-cors-headers
  11. Requirements
  12. ------------
  13. Tested with all combinations of:
  14. * Python: 2.7, 3.6
  15. * Django: 1.8, 1.9, 1.10, 1.11
  16. Setup
  17. -----
  18. Install from **pip**:
  19. .. code-block:: sh
  20. pip install django-cors-headers
  21. and then add it to your installed apps:
  22. .. code-block:: python
  23. INSTALLED_APPS = (
  24. ...
  25. 'corsheaders',
  26. ...
  27. )
  28. You will also need to add a middleware class to listen in on responses:
  29. .. code-block:: python
  30. MIDDLEWARE = [ # Or MIDDLEWARE_CLASSES on Django < 1.10
  31. ...
  32. 'corsheaders.middleware.CorsMiddleware',
  33. 'django.middleware.common.CommonMiddleware',
  34. ...
  35. ]
  36. ``CorsMiddleware`` should be placed as high as possible, especially before any
  37. middleware that can generate responses such as Django's ``CommonMiddleware`` or
  38. Whitenoise's ``WhiteNoiseMiddleware``. If it is not before, it will not be able
  39. to add the CORS headers to these responses.
  40. Also if you are using ``CORS_REPLACE_HTTPS_REFERER`` it should be placed before
  41. Django's ``CsrfViewMiddleware`` (see more below).
  42. Configuration
  43. -------------
  44. Configure the middleware's behaviour in your Django settings. You must add the
  45. hosts that are allowed to do cross-site requests to
  46. ``CORS_ORIGIN_WHITELIST``, or set ``CORS_ORIGIN_ALLOW_ALL`` to ``True``
  47. to allow all hosts.
  48. ``CORS_ORIGIN_ALLOW_ALL``
  49. ~~~~~~~~~~~~~~~~~~~~~~~~~
  50. If ``True``, the whitelist will not be used and all origins will be accepted.
  51. Defaults to ``False``.
  52. ``CORS_ORIGIN_WHITELIST``
  53. ~~~~~~~~~~~~~~~~~~~~~~~~~
  54. A list of origin hostnames that are authorized to make cross-site HTTP
  55. requests. The value ``'null'`` can also appear in this list, and will match the
  56. ``Origin: null`` header that is used in `"privacy-sensitive contexts"
  57. <https://tools.ietf.org/html/rfc6454#section-6>`_, such as when the client is
  58. running from a ``file://`` domain. Defaults to ``[]``.
  59. Example:
  60. .. code-block:: python
  61. CORS_ORIGIN_WHITELIST = (
  62. 'google.com',
  63. 'hostname.example.com',
  64. 'localhost:8000',
  65. '127.0.0.1:9000'
  66. )
  67. ``CORS_ORIGIN_REGEX_WHITELIST``
  68. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  69. A list of regexes that match origin regex list of origin hostnames that are
  70. authorized to make cross-site HTTP requests. Defaults to ``[]``. Useful when
  71. ``CORS_ORIGIN_WHITELIST`` is impractical, such as when you have a large
  72. number of subdomains.
  73. Example:
  74. .. code-block:: python
  75. CORS_ORIGIN_REGEX_WHITELIST = (r'^(https?://)?(\w+\.)?google\.com$', )
  76. --------------
  77. The following are optional settings, for which the defaults probably suffice.
  78. ``CORS_URLS_REGEX``
  79. ~~~~~~~~~~~~~~~~~~~
  80. A regex which restricts the URL's for which the CORS headers will be sent.
  81. Defaults to ``r'^.*$'``, i.e. match all URL's. Useful when you only need CORS
  82. on a part of your site, e.g. an API at ``/api/``.
  83. Example:
  84. .. code-block:: python
  85. CORS_URLS_REGEX = r'^/api/.*$'
  86. ``CORS_ALLOW_METHODS``
  87. ~~~~~~~~~~~~~~~~~~~~~~
  88. A list of HTTP verbs that are allowed for the actual request. Defaults to:
  89. .. code-block:: python
  90. CORS_ALLOW_METHODS = (
  91. 'DELETE',
  92. 'GET',
  93. 'OPTIONS',
  94. 'PATCH',
  95. 'POST',
  96. 'PUT',
  97. )
  98. The default can be imported as ``corsheaders.defaults.default_methods`` so you
  99. can just extend it with your custom methods. This allows you to keep up to date
  100. with any future changes. For example:
  101. .. code-block:: python
  102. from corsheaders.defaults import default_methods
  103. CORS_ALLOW_METHODS = default_methods + (
  104. 'POKE',
  105. )
  106. ``CORS_ALLOW_HEADERS``
  107. ~~~~~~~~~~~~~~~~~~~~~~
  108. The list of non-standard HTTP headers that can be used when making the actual
  109. request. Defaults to:
  110. .. code-block:: python
  111. CORS_ALLOW_HEADERS = (
  112. 'accept',
  113. 'accept-encoding',
  114. 'authorization',
  115. 'content-type',
  116. 'dnt',
  117. 'origin',
  118. 'user-agent',
  119. 'x-csrftoken',
  120. 'x-requested-with',
  121. )
  122. The default can be imported as ``corsheaders.defaults.default_headers`` so you
  123. can extend it with your custom headers. This allows you to keep up to date with
  124. any future changes. For example:
  125. .. code-block:: python
  126. from corsheaders.defaults import default_headers
  127. CORS_ALLOW_HEADERS = default_headers + (
  128. 'my-custom-header',
  129. )
  130. ``CORS_EXPOSE_HEADERS``
  131. ~~~~~~~~~~~~~~~~~~~~~~~
  132. The list of HTTP headers that are to be exposed to the browser. Defaults to
  133. ``[]``.
  134. ``CORS_PREFLIGHT_MAX_AGE``
  135. ~~~~~~~~~~~~~~~~~~~~~~~~~~
  136. The number of seconds a client/browser can cache the preflight response. If
  137. this is 0 (or any falsey value), no max age header will be sent. Defaults to
  138. ``86400`` (one day).
  139. **Note:** A preflight request is an extra request that is made when making a
  140. "not-so-simple" request (e.g. ``Content-Type`` is not
  141. ``application/x-www-form-urlencoded``) to determine what requests the server
  142. actually accepts. Read more about it in the `HTML 5 Rocks CORS tutorial
  143. <https://www.html5rocks.com/en/tutorials/cors/>`_.
  144. ``CORS_ALLOW_CREDENTIALS``
  145. ~~~~~~~~~~~~~~~~~~~~~~~~~~
  146. If ``True``, cookies will be allowed to be included in cross-site HTTP
  147. requests. Defaults to ``False``.
  148. ``CORS_MODEL``
  149. ~~~~~~~~~~~~~~
  150. If set, this should be the path to a model to look up allowed origins, in the
  151. form ``app.modelname``. Defaults to ``None``.
  152. The model should inherit from ``corsheaders.models.AbstractCorsModel`` and specify
  153. the allowed origin in the ``CharField`` called ``cors``.
  154. CSRF Integration
  155. ----------------
  156. Most sites will need to take advantage of the `Cross-Site Request Forgery
  157. protection <https://docs.djangoproject.com/en/dev/ref/csrf/>`_ that Django
  158. offers. CORS and CSRF are separate, and Django has no way of using your CORS
  159. configuration to exempt sites from the ``Referer`` checking that it does on
  160. secure requests. The way to do that is with its `CSRF_TRUSTED_ORIGINS setting
  161. <https://docs.djangoproject.com/en/dev/ref/settings/#csrf-trusted-origins>`_.
  162. For example:
  163. .. code-block:: python
  164. CORS_ORIGIN_WHITELIST = (
  165. 'read.only.com',
  166. 'change.allowed.com',
  167. )
  168. CSRF_TRUSTED_ORIGINS = (
  169. 'change.allowed.com',
  170. )
  171. ``CORS_REPLACE_HTTPS_REFERER``
  172. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  173. ``CSRF_TRUSTED_ORIGINS`` was introduced in Django 1.9, so users of earlier
  174. versions will need an alternate solution. If ``CORS_REPLACE_HTTPS_REFERER`` is
  175. ``True``, ``CorsMiddleware`` will change the ``Referer`` header to something
  176. that will pass Django's CSRF checks whenever the CORS checks pass. Defaults to
  177. ``False``.
  178. Note that unlike ``CSRF_TRUSTED_ORIGINS``, this setting does not allow you to
  179. distinguish between domains that are trusted to *read* resources by CORS and
  180. domains that are trusted to *change* resources by avoiding CSRF protection.
  181. With this feature enabled you should also add
  182. ``corsheaders.middleware.CorsPostCsrfMiddleware`` after
  183. ``django.middleware.csrf.CsrfViewMiddleware`` in your ``MIDDLEWARE_CLASSES`` to
  184. undo the ``Referer`` replacement:
  185. .. code-block:: python
  186. MIDDLEWARE_CLASSES = [
  187. ...
  188. 'corsheaders.middleware.CorsMiddleware',
  189. ...
  190. 'django.middleware.csrf.CsrfViewMiddleware',
  191. 'corsheaders.middleware.CorsPostCsrfMiddleware',
  192. ...
  193. ]
  194. Signals
  195. -------
  196. If you have a use case that requires more than just the above configuration,
  197. you can attach code to check if a given request should be allowed. For example,
  198. this can be used to read the list of origins you allow from a model. Attach any
  199. number of handlers to the ``check_request_enabled``
  200. `Django signal <https://docs.djangoproject.com/en/1.10/ref/signals/>`_, which
  201. provides the ``request`` argument (use ``**kwargs`` in your handler to protect
  202. against any future arguments being added). If any handler attached to the
  203. signal returns a truthy value, the request will be allowed.
  204. For example you might define a handler like this:
  205. .. code-block:: python
  206. # myapp/handlers.py
  207. from corsheaders.signals import check_request_enabled
  208. from .models import MySite
  209. def cors_allow_mysites(sender, request, **kwargs):
  210. return MySite.objects.filter(host=request.host).exists()
  211. check_request_enabled.connect(cors_allow_mysites)
  212. Then connect it at app ready time using a `Django AppConfig
  213. <https://docs.djangoproject.com/en/1.10/ref/applications/>`_:
  214. .. code-block:: python
  215. # myapp/__init__.py
  216. default_app_config = 'myapp.apps.MyAppConfig'
  217. .. code-block:: python
  218. # myapp/apps.py
  219. from django.apps import AppConfig
  220. class MyAppConfig(AppConfig):
  221. name = 'myapp'
  222. def ready(self):
  223. # Makes sure all signal handlers are connected
  224. from . import handlers # noqa
  225. A common use case for the signal is to allow *all* origins to access a subset
  226. of URL's, whilst allowing a normal set of origins to access *all* URL's. This
  227. isn't possible using just the normal configuration, but it can be achieved with
  228. a signal handler.
  229. First set ``CORS_ORIGIN_WHITELIST`` to the list of trusted origins that are
  230. allowed to access every URL, and then add a handler to
  231. ``check_request_enabled`` to allow CORS regardless of the origin for the
  232. unrestricted URL's. For example:
  233. .. code-block:: python
  234. # myapp/handlers.py
  235. from corsheaders.signals import check_request_enabled
  236. def cors_allow_api_to_everyone(sender, request, **kwargs):
  237. return request.path.startswith('/api/')
  238. check_request_enabled.connect(cors_allow_api_to_everyone)
  239. Credits
  240. -------
  241. ``django-cors-headers`` was created by Otto Yiu (`@ottoyiu
  242. <https://github.com/ottoyiu>`_) and has been worked on by `25+ contributors
  243. <https://github.com/ottoyiu/django-cors-headers/graphs/contributors>`_.
  244. Thanks to every contributor, and if you want to get involved please don't
  245. hesitate to make a pull request.
  246. History
  247. =======
  248. Pending
  249. -------
  250. * New release notes go here.
  251. 2.1.0 (2017-05-28)
  252. ------------------
  253. * Django 1.11 compatibility. There were no changes to the actual library code,
  254. so previous versions probably work, though they weren't properly tested on
  255. 1.11.
  256. 2.0.2 (2017-02-06)
  257. ------------------
  258. * Fix when the check for ``CORS_MODEL`` is done to allow it to properly add
  259. the headers and respond to ``OPTIONS`` requests.
  260. 2.0.1 (2017-01-29)
  261. ------------------
  262. * Add support for specifying 'null' in ``CORS_ORIGIN_WHITELIST``.
  263. 2.0.0 (2017-01-07)
  264. ------------------
  265. * Remove previously undocumented ``CorsModel`` as it was causing migration
  266. issues. For backwards compatibility, any users previously using ``CorsModel``
  267. should create a model in their own app that inherits from the new
  268. ``AbstractCorsModel``, and to keep using the same data, set the model's
  269. ``db_table`` to 'corsheaders_corsmodel'. Users not using ``CorsModel``
  270. will find they have an unused table that they can drop.
  271. * Make sure that ``Access-Control-Allow-Credentials`` is in the response if the
  272. client asks for it.
  273. 1.3.1 (2016-11-09)
  274. ------------------
  275. * Fix a bug with the single check if CORS enabled added in 1.3.0: on Django
  276. < 1.10 shortcut responses could be generated by middleware above
  277. ``CorsMiddleware``, before it processed the request, failing with an
  278. ``AttributeError`` for ``request._cors_enabled``. Also clarified the docs
  279. that ``CorsMiddleware`` should be kept as high as possible in your middleware
  280. stack, above any middleware that can generate such responses.
  281. 1.3.0 (2016-11-06)
  282. ------------------
  283. * Add checks to validate the types of the settings.
  284. * Add the 'Do Not Track' header ``'DNT'`` to the default for
  285. ``CORS_ALLOW_HEADERS``.
  286. * Add 'Origin' to the 'Vary' header of outgoing requests when not allowing all
  287. origins, as per the CORS spec. Note this changes the way HTTP caching works
  288. with your CORS-enabled responses.
  289. * Check whether CORS should be enabled on a request only once. This has had a
  290. minor change on the conditions where any custom signals will be called -
  291. signals will now always be called *before* ``HTTP_REFERER`` gets replaced,
  292. whereas before they could be called before and after. Also this attaches the
  293. attribute ``_cors_enabled`` to ``request`` - please take care that other
  294. code you're running does not remove it.
  295. 1.2.2 (2016-10-05)
  296. ------------------
  297. * Add ``CorsModel.__str__`` for human-readable text
  298. * Add a signal that allows you to add code for more intricate control over when
  299. CORS headers are added.
  300. 1.2.1 (2016-09-30)
  301. ------------------
  302. * Made settings dynamically respond to changes, and which allows you to import
  303. the defaults for headers and methods in order to extend them.
  304. 1.2.0 (2016-09-28)
  305. ------------------
  306. * Drop Python 2.6 support.
  307. * Drop Django 1.3-1.7 support, as they are no longer supported.
  308. * Confirmed Django 1.9 support (no changes outside of tests were necessary).
  309. * Added Django 1.10 support.
  310. * Package as a universal wheel.
  311. 1.1.0 (2014-12-15)
  312. ------------------
  313. * django-cors-header now supports Django 1.8 with its new application loading
  314. system! Thanks @jpadilla for making this possible and sorry for the delay in
  315. making a release.
  316. 1.0.0 (2014-12-13)
  317. ------------------
  318. django-cors-headers is all grown-up :) Since it's been used in production for
  319. many many deployments, I think it's time we mark this as a stable release.
  320. * Switching this middleware versioning over to semantic versioning
  321. * #46 add user-agent and accept-encoding default headers
  322. * #45 pep-8 this big boy up
  323. 0.13 (2014-08-14)
  324. -----------------
  325. * Add support for Python 3
  326. * Updated tests
  327. * Improved docuemntation
  328. * Small bugfixes
  329. 0.12 (2013-09-24)
  330. -----------------
  331. * Added an option to selectively enable CORS only for specific URLs
  332. 0.11 (2013-09-24)
  333. * Added the ability to specify a regex for whitelisting many origin hostnames
  334. at once
  335. 0.10 (2013-09-05)
  336. -----------------
  337. * Introduced port distinction for origin checking
  338. * Use ``urlparse`` for Python 3 support
  339. * Added testcases to project
  340. 0.06 (2013-02-18)
  341. -----------------
  342. * Add support for exposed response headers
  343. 0.05 (2013-01-26)
  344. -----------------
  345. * Fixed middleware to ensure correct response for CORS preflight requests
  346. 0.04 (2013-01-25)
  347. -----------------
  348. * Add ``Access-Control-Allow-Credentials`` control to simple requests
  349. 0.03 (2013-01-22)
  350. -----------------
  351. * Bugfix to repair mismatched default variable names
  352. 0.02 (2013-01-19)
  353. -----------------
  354. * Refactor/pull defaults into separate file
  355. 0.01 (2013-01-19)
  356. -----------------
  357. * Initial release