django-cors-headers


Namedjango-cors-headers JSON
Version 4.3.1 PyPI version JSON
download
home_page
Summarydjango-cors-headers is a Django application for handling the server headers required for Cross-Origin Resource Sharing (CORS).
upload_time2023-11-14 17:27:29
maintainer
docs_urlNone
author
requires_python>=3.8
licenseMIT
keywords api cors django middleware rest
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage No coveralls.
            ===================
django-cors-headers
===================

.. image:: https://img.shields.io/github/actions/workflow/status/adamchainz/django-cors-headers/main.yml?branch=main&style=for-the-badge
   :target: https://github.com/adamchainz/django-cors-headers/actions?workflow=CI

.. image:: https://img.shields.io/badge/Coverage-100%25-success?style=for-the-badge
  :target: https://github.com/adamchainz/django-cors-headers/actions?workflow=CI

.. image:: https://img.shields.io/pypi/v/django-cors-headers.svg?style=for-the-badge
    :target: https://pypi.org/project/django-cors-headers/

.. image:: https://img.shields.io/badge/code%20style-black-000000.svg?style=for-the-badge
    :target: https://github.com/psf/black

.. image:: https://img.shields.io/badge/pre--commit-enabled-brightgreen?logo=pre-commit&logoColor=white&style=for-the-badge
   :target: https://github.com/pre-commit/pre-commit
   :alt: pre-commit

A Django App that adds Cross-Origin Resource Sharing (CORS) headers to
responses. This allows in-browser requests to your Django application from
other origins.

----

**Improve your Django and Git skills** with `my books <https://adamj.eu/books/>`__.

----

About CORS
----------

Adding CORS headers allows your resources to be accessed on other domains. It's
important you understand the implications before adding the headers, since you
could be unintentionally opening up your site's private data to others.

Some good resources to read on the subject are:

* Julia Evans' `introductory comic <https://drawings.jvns.ca/cors/>`__ and
  `educational quiz <https://questions.wizardzines.com/cors.html>`__.
* Jake Archibald’s `How to win at CORS <https://jakearchibald.com/2021/cors/>`__
* The `MDN Article <https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS>`_
* The `HTML5 Rocks Tutorial <https://www.html5rocks.com/en/tutorials/cors/>`_
* The `Wikipedia Page <https://en.wikipedia.org/wiki/Cross-origin_resource_sharing>`_

Requirements
------------

Python 3.8 to 3.12 supported.

Django 3.2 to 5.0 supported.

Setup
-----

Install from **pip**:

.. code-block:: sh

    python -m pip install django-cors-headers

and then add it to your installed apps:

.. code-block:: python

    INSTALLED_APPS = [
        ...,
        "corsheaders",
        ...,
    ]

Make sure you add the trailing comma or you might get a ``ModuleNotFoundError``
(see `this blog
post <https://adamj.eu/tech/2020/06/29/why-does-python-raise-modulenotfounderror-when-modifying-installed-apps/>`__).

You will also need to add a middleware class to listen in on responses:

.. code-block:: python

    MIDDLEWARE = [
        ...,
        "corsheaders.middleware.CorsMiddleware",
        "django.middleware.common.CommonMiddleware",
        ...,
    ]

``CorsMiddleware`` should be placed as high as possible, especially before any
middleware that can generate responses such as Django's ``CommonMiddleware`` or
Whitenoise's ``WhiteNoiseMiddleware``. If it is not before, it will not be able
to add the CORS headers to these responses.

About
-----

**django-cors-headers** was created in January 2013 by Otto Yiu. It went
unmaintained from August 2015 and was forked in January 2016 to the package
`django-cors-middleware <https://github.com/zestedesavoir/django-cors-middleware>`_
by Laville Augustin at Zeste de Savoir.
In September 2016, Adam Johnson, Ed Morley, and others gained maintenance
responsibility for **django-cors-headers**
(`Issue 110 <https://github.com/adamchainz/django-cors-headers/issues/110>`__)
from Otto Yiu.
Basically all of the changes in the forked **django-cors-middleware** were
merged back, or re-implemented in a different way, so it should be possible to
switch back. If there's a feature that hasn't been merged, please open an issue
about it.

**django-cors-headers** has had `40+ contributors
<https://github.com/adamchainz/django-cors-headers/graphs/contributors>`__
in its time; thanks to every one of them.

Configuration
-------------

Configure the middleware's behaviour in your Django settings. You must set at
least one of three following settings:

* ``CORS_ALLOWED_ORIGINS``
* ``CORS_ALLOWED_ORIGIN_REGEXES``
* ``CORS_ALLOW_ALL_ORIGINS``

``CORS_ALLOWED_ORIGINS: Sequence[str]``
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

A list of origins that are authorized to make cross-site HTTP requests.
The origins in this setting will be allowed, and the requesting origin will be echoed back to the client in the |access-control-allow-origin header|__.
Defaults to ``[]``.

.. |access-control-allow-origin header| replace:: ``access-control-allow-origin`` header
__ https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Origin

An Origin is defined by `the CORS RFC Section 3.2 <https://tools.ietf.org/html/rfc6454#section-3.2>`_ as a URI scheme + hostname + port, or one of the special values ``'null'`` or ``'file://'``.
Default ports (HTTPS = 443, HTTP = 80) are optional.

The special value ``null`` is sent by the browser in `"privacy-sensitive contexts" <https://tools.ietf.org/html/rfc6454#section-6>`__, such as when the client is running from a ``file://`` domain.
The special value `file://` is sent accidentally by some versions of Chrome on Android as per `this bug <https://bugs.chromium.org/p/chromium/issues/detail?id=991107>`__.

Example:

.. code-block:: python

    CORS_ALLOWED_ORIGINS = [
        "https://example.com",
        "https://sub.example.com",
        "http://localhost:8080",
        "http://127.0.0.1:9000",
    ]

Previously this setting was called ``CORS_ORIGIN_WHITELIST``, which still works as an alias, with the new name taking precedence.

``CORS_ALLOWED_ORIGIN_REGEXES: Sequence[str | Pattern[str]]``
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

A list of strings representing regexes that match Origins that are authorized to make cross-site HTTP requests.
Defaults to ``[]``.
Useful when ``CORS_ALLOWED_ORIGINS`` is impractical, such as when you have a large number of subdomains.

Example:

.. code-block:: python

    CORS_ALLOWED_ORIGIN_REGEXES = [
        r"^https://\w+\.example\.com$",
    ]

Previously this setting was called ``CORS_ORIGIN_REGEX_WHITELIST``, which still works as an alias, with the new name taking precedence.

``CORS_ALLOW_ALL_ORIGINS: bool``
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

If ``True``, all origins will be allowed.
Other settings restricting allowed origins will be ignored.
Defaults to ``False``.

Setting this to ``True`` can be *dangerous*, as it allows any website to make cross-origin requests to yours.
Generally you'll want to restrict the list of allowed origins with ``CORS_ALLOWED_ORIGINS`` or ``CORS_ALLOWED_ORIGIN_REGEXES``.

Previously this setting was called ``CORS_ORIGIN_ALLOW_ALL``, which still works as an alias, with the new name taking precedence.

--------------

The following are optional settings, for which the defaults probably suffice.

``CORS_URLS_REGEX: str | Pattern[str]``
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

A regex which restricts the URL's for which the CORS headers will be sent.
Defaults to ``r'^.*$'``, i.e. match all URL's.
Useful when you only need CORS on a part of your site, e.g. an API at ``/api/``.

Example:

.. code-block:: python

    CORS_URLS_REGEX = r"^/api/.*$"

``CORS_ALLOW_METHODS: Sequence[str]``
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

A list of HTTP verbs that are allowed for the actual request.
Defaults to:

.. code-block:: python

    CORS_ALLOW_METHODS = (
        "DELETE",
        "GET",
        "OPTIONS",
        "PATCH",
        "POST",
        "PUT",
    )

The default can be imported as ``corsheaders.defaults.default_methods`` so you can just extend it with your custom methods.
This allows you to keep up to date with any future changes.
For example:

.. code-block:: python

    from corsheaders.defaults import default_methods

    CORS_ALLOW_METHODS = (
        *default_methods,
        "POKE",
    )

``CORS_ALLOW_HEADERS: Sequence[str]``
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

The list of non-standard HTTP headers that you permit in requests from the browser.
Sets the |Access-Control-Allow-Headers header|__ in responses to `preflight requests <https://developer.mozilla.org/en-US/docs/Glossary/Preflight_request>`__.
Defaults to:

.. |Access-Control-Allow-Headers header| replace:: ``Access-Control-Allow-Headers`` header
__ https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Headers

.. code-block:: python

    CORS_ALLOW_HEADERS = (
        "accept",
        "authorization",
        "content-type",
        "user-agent",
        "x-csrftoken",
        "x-requested-with",
    )

The default can be imported as ``corsheaders.defaults.default_headers`` so you can extend it with your custom headers.
This allows you to keep up to date with any future changes.
For example:

.. code-block:: python

    from corsheaders.defaults import default_headers

    CORS_ALLOW_HEADERS = (
        *default_headers,
        "my-custom-header",
    )

``CORS_EXPOSE_HEADERS: Sequence[str]``
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

The list of extra HTTP headers to expose to the browser, in addition to the default `safelisted headers <https://developer.mozilla.org/en-US/docs/Glossary/CORS-safelisted_response_header>`__.
If non-empty, these are declared in the |access-control-expose-headers header|__.
Defaults to ``[]``.

.. |access-control-expose-headers header| replace:: ``access-control-expose-headers`` header
__ https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Expose-Headers

``CORS_PREFLIGHT_MAX_AGE: int``
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

The number of seconds the browser can cache the preflight response.
This sets the |access-control-max-age header|__ in preflight responses.
If this is 0 (or any falsey value), no max age header will be sent.
Defaults to ``86400`` (one day).

.. |access-control-max-age header| replace:: ``access-control-max-age`` header
__ https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Max-Age

**Note:**
Browsers send `preflight requests <https://developer.mozilla.org/en-US/docs/Glossary/Preflight_request>`__ before certain “non-simple” requests, to check they will be allowed.
Read more about it in the `CORS MDN article <https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS#preflighted_requests>`_.

``CORS_ALLOW_CREDENTIALS: bool``
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

If ``True``, cookies will be allowed to be included in cross-site HTTP requests.
This sets the |access-control-allow-credentials header|__ in preflight and normal responses.
Defaults to ``False``.

.. |access-control-allow-credentials header| replace:: ``Access-Control-Allow-Credentials`` header
__ https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/access-control-allow-credentials

Note: in Django 2.1 the `SESSION_COOKIE_SAMESITE`_ setting was added, set to ``'Lax'`` by default, which will prevent Django's session cookie being sent cross-domain.
Change the setting to ``'None'`` if you need to bypass this security restriction.

.. _SESSION_COOKIE_SAMESITE: https://docs.djangoproject.com/en/stable/ref/settings/#std:setting-SESSION_COOKIE_SAMESITE

``CORS_ALLOW_PRIVATE_NETWORK: bool``
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

If ``True``, allow requests from sites on “public” IP to this server on a “private” IP.
In such cases, browsers send an extra CORS header ``access-control-request-private-network``, for which ``OPTIONS`` responses must contain ``access-control-allow-private-network: true``.

Refer to:

* `Local Network Access <https://wicg.github.io/local-network-access/>`__, the W3C Community Draft specification.
* `Private Network Access: introducing preflights <https://developer.chrome.com/blog/private-network-access-preflight/>`__, a blog post from the Google Chrome team.

CSRF Integration
----------------

Most sites will need to take advantage of the `Cross-Site Request Forgery
protection <https://docs.djangoproject.com/en/stable/ref/csrf/>`_ that Django
offers. CORS and CSRF are separate, and Django has no way of using your CORS
configuration to exempt sites from the ``Referer`` checking that it does on
secure requests. The way to do that is with its `CSRF_TRUSTED_ORIGINS setting
<https://docs.djangoproject.com/en/stable/ref/settings/#csrf-trusted-origins>`_.
For example:

.. code-block:: python

    CORS_ALLOWED_ORIGINS = [
        "https://read-only.example.com",
        "https://read-and-write.example.com",
    ]

    CSRF_TRUSTED_ORIGINS = [
        "https://read-and-write.example.com",
    ]

Signals
-------

If you have a use case that requires more than just the above configuration,
you can attach code to check if a given request should be allowed. For example,
this can be used to read the list of origins you allow from a model. Attach any
number of handlers to the ``check_request_enabled``
`Django signal <https://docs.djangoproject.com/en/stable/ref/signals/>`_, which
provides the ``request`` argument (use ``**kwargs`` in your handler to protect
against any future arguments being added). If any handler attached to the
signal returns a truthy value, the request will be allowed.

For example you might define a handler like this:

.. code-block:: python

    # myapp/handlers.py
    from corsheaders.signals import check_request_enabled

    from myapp.models import MySite


    def cors_allow_mysites(sender, request, **kwargs):
        return MySite.objects.filter(host=request.headers["origin"]).exists()


    check_request_enabled.connect(cors_allow_mysites)

Then connect it at app ready time using a `Django AppConfig
<https://docs.djangoproject.com/en/stable/ref/applications/>`_:

.. code-block:: python

    # myapp/__init__.py

    default_app_config = "myapp.apps.MyAppConfig"

.. code-block:: python

    # myapp/apps.py

    from django.apps import AppConfig


    class MyAppConfig(AppConfig):
        name = "myapp"

        def ready(self):
            # Makes sure all signal handlers are connected
            from myapp import handlers  # noqa

A common use case for the signal is to allow *all* origins to access a subset
of URL's, whilst allowing a normal set of origins to access *all* URL's. This
isn't possible using just the normal configuration, but it can be achieved with
a signal handler.

First set ``CORS_ALLOWED_ORIGINS`` to the list of trusted origins that are
allowed to access every URL, and then add a handler to
``check_request_enabled`` to allow CORS regardless of the origin for the
unrestricted URL's. For example:

.. code-block:: python

    # myapp/handlers.py
    from corsheaders.signals import check_request_enabled


    def cors_allow_api_to_everyone(sender, request, **kwargs):
        return request.path.startswith("/api/")


    check_request_enabled.connect(cors_allow_api_to_everyone)

            

Raw data

            {
    "_id": null,
    "home_page": "",
    "name": "django-cors-headers",
    "maintainer": "",
    "docs_url": null,
    "requires_python": ">=3.8",
    "maintainer_email": "Adam Johnson <me@adamj.eu>",
    "keywords": "api,cors,django,middleware,rest",
    "author": "",
    "author_email": "Otto Yiu <otto@live.ca>",
    "download_url": "https://files.pythonhosted.org/packages/8a/04/a280a98256602d3f4fffae37a9410711fb80f9d6cf199679f6e93bbdb8b3/django-cors-headers-4.3.1.tar.gz",
    "platform": null,
    "description": "===================\ndjango-cors-headers\n===================\n\n.. image:: https://img.shields.io/github/actions/workflow/status/adamchainz/django-cors-headers/main.yml?branch=main&style=for-the-badge\n   :target: https://github.com/adamchainz/django-cors-headers/actions?workflow=CI\n\n.. image:: https://img.shields.io/badge/Coverage-100%25-success?style=for-the-badge\n  :target: https://github.com/adamchainz/django-cors-headers/actions?workflow=CI\n\n.. image:: https://img.shields.io/pypi/v/django-cors-headers.svg?style=for-the-badge\n    :target: https://pypi.org/project/django-cors-headers/\n\n.. image:: https://img.shields.io/badge/code%20style-black-000000.svg?style=for-the-badge\n    :target: https://github.com/psf/black\n\n.. image:: https://img.shields.io/badge/pre--commit-enabled-brightgreen?logo=pre-commit&logoColor=white&style=for-the-badge\n   :target: https://github.com/pre-commit/pre-commit\n   :alt: pre-commit\n\nA Django App that adds Cross-Origin Resource Sharing (CORS) headers to\nresponses. This allows in-browser requests to your Django application from\nother origins.\n\n----\n\n**Improve your Django and Git skills** with `my books <https://adamj.eu/books/>`__.\n\n----\n\nAbout CORS\n----------\n\nAdding CORS headers allows your resources to be accessed on other domains. It's\nimportant you understand the implications before adding the headers, since you\ncould be unintentionally opening up your site's private data to others.\n\nSome good resources to read on the subject are:\n\n* Julia Evans' `introductory comic <https://drawings.jvns.ca/cors/>`__ and\n  `educational quiz <https://questions.wizardzines.com/cors.html>`__.\n* Jake Archibald\u2019s `How to win at CORS <https://jakearchibald.com/2021/cors/>`__\n* The `MDN Article <https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS>`_\n* The `HTML5 Rocks Tutorial <https://www.html5rocks.com/en/tutorials/cors/>`_\n* The `Wikipedia Page <https://en.wikipedia.org/wiki/Cross-origin_resource_sharing>`_\n\nRequirements\n------------\n\nPython 3.8 to 3.12 supported.\n\nDjango 3.2 to 5.0 supported.\n\nSetup\n-----\n\nInstall from **pip**:\n\n.. code-block:: sh\n\n    python -m pip install django-cors-headers\n\nand then add it to your installed apps:\n\n.. code-block:: python\n\n    INSTALLED_APPS = [\n        ...,\n        \"corsheaders\",\n        ...,\n    ]\n\nMake sure you add the trailing comma or you might get a ``ModuleNotFoundError``\n(see `this blog\npost <https://adamj.eu/tech/2020/06/29/why-does-python-raise-modulenotfounderror-when-modifying-installed-apps/>`__).\n\nYou will also need to add a middleware class to listen in on responses:\n\n.. code-block:: python\n\n    MIDDLEWARE = [\n        ...,\n        \"corsheaders.middleware.CorsMiddleware\",\n        \"django.middleware.common.CommonMiddleware\",\n        ...,\n    ]\n\n``CorsMiddleware`` should be placed as high as possible, especially before any\nmiddleware that can generate responses such as Django's ``CommonMiddleware`` or\nWhitenoise's ``WhiteNoiseMiddleware``. If it is not before, it will not be able\nto add the CORS headers to these responses.\n\nAbout\n-----\n\n**django-cors-headers** was created in January 2013 by Otto Yiu. It went\nunmaintained from August 2015 and was forked in January 2016 to the package\n`django-cors-middleware <https://github.com/zestedesavoir/django-cors-middleware>`_\nby Laville Augustin at Zeste de Savoir.\nIn September 2016, Adam Johnson, Ed Morley, and others gained maintenance\nresponsibility for **django-cors-headers**\n(`Issue 110 <https://github.com/adamchainz/django-cors-headers/issues/110>`__)\nfrom Otto Yiu.\nBasically all of the changes in the forked **django-cors-middleware** were\nmerged back, or re-implemented in a different way, so it should be possible to\nswitch back. If there's a feature that hasn't been merged, please open an issue\nabout it.\n\n**django-cors-headers** has had `40+ contributors\n<https://github.com/adamchainz/django-cors-headers/graphs/contributors>`__\nin its time; thanks to every one of them.\n\nConfiguration\n-------------\n\nConfigure the middleware's behaviour in your Django settings. You must set at\nleast one of three following settings:\n\n* ``CORS_ALLOWED_ORIGINS``\n* ``CORS_ALLOWED_ORIGIN_REGEXES``\n* ``CORS_ALLOW_ALL_ORIGINS``\n\n``CORS_ALLOWED_ORIGINS: Sequence[str]``\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nA list of origins that are authorized to make cross-site HTTP requests.\nThe origins in this setting will be allowed, and the requesting origin will be echoed back to the client in the |access-control-allow-origin header|__.\nDefaults to ``[]``.\n\n.. |access-control-allow-origin header| replace:: ``access-control-allow-origin`` header\n__ https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Origin\n\nAn Origin is defined by `the CORS RFC Section 3.2 <https://tools.ietf.org/html/rfc6454#section-3.2>`_ as a URI scheme + hostname + port, or one of the special values ``'null'`` or ``'file://'``.\nDefault ports (HTTPS = 443, HTTP = 80) are optional.\n\nThe special value ``null`` is sent by the browser in `\"privacy-sensitive contexts\" <https://tools.ietf.org/html/rfc6454#section-6>`__, such as when the client is running from a ``file://`` domain.\nThe special value `file://` is sent accidentally by some versions of Chrome on Android as per `this bug <https://bugs.chromium.org/p/chromium/issues/detail?id=991107>`__.\n\nExample:\n\n.. code-block:: python\n\n    CORS_ALLOWED_ORIGINS = [\n        \"https://example.com\",\n        \"https://sub.example.com\",\n        \"http://localhost:8080\",\n        \"http://127.0.0.1:9000\",\n    ]\n\nPreviously this setting was called ``CORS_ORIGIN_WHITELIST``, which still works as an alias, with the new name taking precedence.\n\n``CORS_ALLOWED_ORIGIN_REGEXES: Sequence[str | Pattern[str]]``\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nA list of strings representing regexes that match Origins that are authorized to make cross-site HTTP requests.\nDefaults to ``[]``.\nUseful when ``CORS_ALLOWED_ORIGINS`` is impractical, such as when you have a large number of subdomains.\n\nExample:\n\n.. code-block:: python\n\n    CORS_ALLOWED_ORIGIN_REGEXES = [\n        r\"^https://\\w+\\.example\\.com$\",\n    ]\n\nPreviously this setting was called ``CORS_ORIGIN_REGEX_WHITELIST``, which still works as an alias, with the new name taking precedence.\n\n``CORS_ALLOW_ALL_ORIGINS: bool``\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nIf ``True``, all origins will be allowed.\nOther settings restricting allowed origins will be ignored.\nDefaults to ``False``.\n\nSetting this to ``True`` can be *dangerous*, as it allows any website to make cross-origin requests to yours.\nGenerally you'll want to restrict the list of allowed origins with ``CORS_ALLOWED_ORIGINS`` or ``CORS_ALLOWED_ORIGIN_REGEXES``.\n\nPreviously this setting was called ``CORS_ORIGIN_ALLOW_ALL``, which still works as an alias, with the new name taking precedence.\n\n--------------\n\nThe following are optional settings, for which the defaults probably suffice.\n\n``CORS_URLS_REGEX: str | Pattern[str]``\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nA regex which restricts the URL's for which the CORS headers will be sent.\nDefaults to ``r'^.*$'``, i.e. match all URL's.\nUseful when you only need CORS on a part of your site, e.g. an API at ``/api/``.\n\nExample:\n\n.. code-block:: python\n\n    CORS_URLS_REGEX = r\"^/api/.*$\"\n\n``CORS_ALLOW_METHODS: Sequence[str]``\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nA list of HTTP verbs that are allowed for the actual request.\nDefaults to:\n\n.. code-block:: python\n\n    CORS_ALLOW_METHODS = (\n        \"DELETE\",\n        \"GET\",\n        \"OPTIONS\",\n        \"PATCH\",\n        \"POST\",\n        \"PUT\",\n    )\n\nThe default can be imported as ``corsheaders.defaults.default_methods`` so you can just extend it with your custom methods.\nThis allows you to keep up to date with any future changes.\nFor example:\n\n.. code-block:: python\n\n    from corsheaders.defaults import default_methods\n\n    CORS_ALLOW_METHODS = (\n        *default_methods,\n        \"POKE\",\n    )\n\n``CORS_ALLOW_HEADERS: Sequence[str]``\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nThe list of non-standard HTTP headers that you permit in requests from the browser.\nSets the |Access-Control-Allow-Headers header|__ in responses to `preflight requests <https://developer.mozilla.org/en-US/docs/Glossary/Preflight_request>`__.\nDefaults to:\n\n.. |Access-Control-Allow-Headers header| replace:: ``Access-Control-Allow-Headers`` header\n__ https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Headers\n\n.. code-block:: python\n\n    CORS_ALLOW_HEADERS = (\n        \"accept\",\n        \"authorization\",\n        \"content-type\",\n        \"user-agent\",\n        \"x-csrftoken\",\n        \"x-requested-with\",\n    )\n\nThe default can be imported as ``corsheaders.defaults.default_headers`` so you can extend it with your custom headers.\nThis allows you to keep up to date with any future changes.\nFor example:\n\n.. code-block:: python\n\n    from corsheaders.defaults import default_headers\n\n    CORS_ALLOW_HEADERS = (\n        *default_headers,\n        \"my-custom-header\",\n    )\n\n``CORS_EXPOSE_HEADERS: Sequence[str]``\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nThe list of extra HTTP headers to expose to the browser, in addition to the default `safelisted headers <https://developer.mozilla.org/en-US/docs/Glossary/CORS-safelisted_response_header>`__.\nIf non-empty, these are declared in the |access-control-expose-headers header|__.\nDefaults to ``[]``.\n\n.. |access-control-expose-headers header| replace:: ``access-control-expose-headers`` header\n__ https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Expose-Headers\n\n``CORS_PREFLIGHT_MAX_AGE: int``\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nThe number of seconds the browser can cache the preflight response.\nThis sets the |access-control-max-age header|__ in preflight responses.\nIf this is 0 (or any falsey value), no max age header will be sent.\nDefaults to ``86400`` (one day).\n\n.. |access-control-max-age header| replace:: ``access-control-max-age`` header\n__ https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Max-Age\n\n**Note:**\nBrowsers send `preflight requests <https://developer.mozilla.org/en-US/docs/Glossary/Preflight_request>`__ before certain \u201cnon-simple\u201d requests, to check they will be allowed.\nRead more about it in the `CORS MDN article <https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS#preflighted_requests>`_.\n\n``CORS_ALLOW_CREDENTIALS: bool``\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nIf ``True``, cookies will be allowed to be included in cross-site HTTP requests.\nThis sets the |access-control-allow-credentials header|__ in preflight and normal responses.\nDefaults to ``False``.\n\n.. |access-control-allow-credentials header| replace:: ``Access-Control-Allow-Credentials`` header\n__ https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/access-control-allow-credentials\n\nNote: in Django 2.1 the `SESSION_COOKIE_SAMESITE`_ setting was added, set to ``'Lax'`` by default, which will prevent Django's session cookie being sent cross-domain.\nChange the setting to ``'None'`` if you need to bypass this security restriction.\n\n.. _SESSION_COOKIE_SAMESITE: https://docs.djangoproject.com/en/stable/ref/settings/#std:setting-SESSION_COOKIE_SAMESITE\n\n``CORS_ALLOW_PRIVATE_NETWORK: bool``\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nIf ``True``, allow requests from sites on \u201cpublic\u201d IP to this server on a \u201cprivate\u201d IP.\nIn such cases, browsers send an extra CORS header ``access-control-request-private-network``, for which ``OPTIONS`` responses must contain ``access-control-allow-private-network: true``.\n\nRefer to:\n\n* `Local Network Access <https://wicg.github.io/local-network-access/>`__, the W3C Community Draft specification.\n* `Private Network Access: introducing preflights <https://developer.chrome.com/blog/private-network-access-preflight/>`__, a blog post from the Google Chrome team.\n\nCSRF Integration\n----------------\n\nMost sites will need to take advantage of the `Cross-Site Request Forgery\nprotection <https://docs.djangoproject.com/en/stable/ref/csrf/>`_ that Django\noffers. CORS and CSRF are separate, and Django has no way of using your CORS\nconfiguration to exempt sites from the ``Referer`` checking that it does on\nsecure requests. The way to do that is with its `CSRF_TRUSTED_ORIGINS setting\n<https://docs.djangoproject.com/en/stable/ref/settings/#csrf-trusted-origins>`_.\nFor example:\n\n.. code-block:: python\n\n    CORS_ALLOWED_ORIGINS = [\n        \"https://read-only.example.com\",\n        \"https://read-and-write.example.com\",\n    ]\n\n    CSRF_TRUSTED_ORIGINS = [\n        \"https://read-and-write.example.com\",\n    ]\n\nSignals\n-------\n\nIf you have a use case that requires more than just the above configuration,\nyou can attach code to check if a given request should be allowed. For example,\nthis can be used to read the list of origins you allow from a model. Attach any\nnumber of handlers to the ``check_request_enabled``\n`Django signal <https://docs.djangoproject.com/en/stable/ref/signals/>`_, which\nprovides the ``request`` argument (use ``**kwargs`` in your handler to protect\nagainst any future arguments being added). If any handler attached to the\nsignal returns a truthy value, the request will be allowed.\n\nFor example you might define a handler like this:\n\n.. code-block:: python\n\n    # myapp/handlers.py\n    from corsheaders.signals import check_request_enabled\n\n    from myapp.models import MySite\n\n\n    def cors_allow_mysites(sender, request, **kwargs):\n        return MySite.objects.filter(host=request.headers[\"origin\"]).exists()\n\n\n    check_request_enabled.connect(cors_allow_mysites)\n\nThen connect it at app ready time using a `Django AppConfig\n<https://docs.djangoproject.com/en/stable/ref/applications/>`_:\n\n.. code-block:: python\n\n    # myapp/__init__.py\n\n    default_app_config = \"myapp.apps.MyAppConfig\"\n\n.. code-block:: python\n\n    # myapp/apps.py\n\n    from django.apps import AppConfig\n\n\n    class MyAppConfig(AppConfig):\n        name = \"myapp\"\n\n        def ready(self):\n            # Makes sure all signal handlers are connected\n            from myapp import handlers  # noqa\n\nA common use case for the signal is to allow *all* origins to access a subset\nof URL's, whilst allowing a normal set of origins to access *all* URL's. This\nisn't possible using just the normal configuration, but it can be achieved with\na signal handler.\n\nFirst set ``CORS_ALLOWED_ORIGINS`` to the list of trusted origins that are\nallowed to access every URL, and then add a handler to\n``check_request_enabled`` to allow CORS regardless of the origin for the\nunrestricted URL's. For example:\n\n.. code-block:: python\n\n    # myapp/handlers.py\n    from corsheaders.signals import check_request_enabled\n\n\n    def cors_allow_api_to_everyone(sender, request, **kwargs):\n        return request.path.startswith(\"/api/\")\n\n\n    check_request_enabled.connect(cors_allow_api_to_everyone)\n",
    "bugtrack_url": null,
    "license": "MIT",
    "summary": "django-cors-headers is a Django application for handling the server headers required for Cross-Origin Resource Sharing (CORS).",
    "version": "4.3.1",
    "project_urls": {
        "Changelog": "https://github.com/adamchainz/django-cors-headers/blob/main/CHANGELOG.rst",
        "Funding": "https://adamj.eu/books/",
        "Repository": "https://github.com/adamchainz/django-cors-headers"
    },
    "split_keywords": [
        "api",
        "cors",
        "django",
        "middleware",
        "rest"
    ],
    "urls": [
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "fe6a3428ab5d1ec270e845f4ef064a7cefbf1339b4454788d77c00d36caa828c",
                "md5": "40e07fd2c986d85c5ca1c5b0de4ffcf7",
                "sha256": "0b1fd19297e37417fc9f835d39e45c8c642938ddba1acce0c1753d3edef04f36"
            },
            "downloads": -1,
            "filename": "django_cors_headers-4.3.1-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "40e07fd2c986d85c5ca1c5b0de4ffcf7",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": ">=3.8",
            "size": 12785,
            "upload_time": "2023-11-14T17:27:27",
            "upload_time_iso_8601": "2023-11-14T17:27:27.128313Z",
            "url": "https://files.pythonhosted.org/packages/fe/6a/3428ab5d1ec270e845f4ef064a7cefbf1339b4454788d77c00d36caa828c/django_cors_headers-4.3.1-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "8a04a280a98256602d3f4fffae37a9410711fb80f9d6cf199679f6e93bbdb8b3",
                "md5": "1b47865471f7d3d62821a56d4e01de5e",
                "sha256": "0bf65ef45e606aff1994d35503e6b677c0b26cafff6506f8fd7187f3be840207"
            },
            "downloads": -1,
            "filename": "django-cors-headers-4.3.1.tar.gz",
            "has_sig": false,
            "md5_digest": "1b47865471f7d3d62821a56d4e01de5e",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": ">=3.8",
            "size": 21146,
            "upload_time": "2023-11-14T17:27:29",
            "upload_time_iso_8601": "2023-11-14T17:27:29.310662Z",
            "url": "https://files.pythonhosted.org/packages/8a/04/a280a98256602d3f4fffae37a9410711fb80f9d6cf199679f6e93bbdb8b3/django-cors-headers-4.3.1.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2023-11-14 17:27:29",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "github_user": "adamchainz",
    "github_project": "django-cors-headers",
    "travis_ci": false,
    "coveralls": false,
    "github_actions": true,
    "tox": true,
    "lcname": "django-cors-headers"
}
        
Elapsed time: 0.13603s