Django app for handling the server headers required for Cross-Origin Resource Sharing (CORS)

Overview

django-cors-headers

https://img.shields.io/github/workflow/status/adamchainz/django-cors-headers/CI/main?style=for-the-badge https://img.shields.io/coveralls/github/adamchainz/django-cors-headers/main?style=for-the-badge https://img.shields.io/pypi/v/django-cors-headers.svg?style=for-the-badge https://img.shields.io/badge/code%20style-black-000000.svg?style=for-the-badge 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.

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:

Requirements

Python 3.6 to 3.9 supported.

Django 2.2 to 3.2 supported.


Are your tests slow? Check out my book Speed Up Your Django Tests which covers loads of best practices so you can write faster, more accurate tests.


Setup

Install from pip:

python -m pip install django-cors-headers

and then add it to your installed apps:

INSTALLED_APPS = [
    ...
    'corsheaders',
    ...
]

Make sure you add the trailing comma or you might get a ModuleNotFoundError (see this blog post).

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

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.

Also if you are using CORS_REPLACE_HTTPS_REFERER it should be placed before Django's CsrfViewMiddleware (see more below).

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 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) 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 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

A list of origins that are authorized to make cross-site HTTP requests. Defaults to [].

An Origin is defined by the CORS RFC 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 here.

The special value null is sent by the browser in "privacy-sensitive contexts", 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.

Example:

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

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:

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

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

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:

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

CORS_ALLOW_METHODS

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

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:

from corsheaders.defaults import default_methods

CORS_ALLOW_METHODS = list(default_methods) + [
    'POKE',
]

CORS_ALLOW_HEADERS

The list of non-standard HTTP headers that can be used when making the actual request. Defaults to:

CORS_ALLOW_HEADERS = [
    'accept',
    'accept-encoding',
    'authorization',
    'content-type',
    'dnt',
    'origin',
    '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:

from corsheaders.defaults import default_headers

CORS_ALLOW_HEADERS = list(default_headers) + [
    'my-custom-header',
]

CORS_EXPOSE_HEADERS

The list of HTTP headers that are to be exposed to the browser. Defaults to [].

CORS_PREFLIGHT_MAX_AGE

The number of seconds a client/browser can cache the preflight response. If this is 0 (or any falsey value), no max age header will be sent. Defaults to 86400 (one day).

Note: A preflight request is an extra request that is made when making a "not-so-simple" request (e.g. Content-Type is not application/x-www-form-urlencoded) to determine what requests the server actually accepts. Read more about it in the CORS MDN article.

CORS_ALLOW_CREDENTIALS

If True, cookies will be allowed to be included in cross-site HTTP requests. Defaults to False.

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 it to None to bypass this security restriction.

CSRF Integration

Most sites will need to take advantage of the Cross-Site Request Forgery protection 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. For example:

CORS_ALLOWED_ORIGINS = [
    'http://read.only.com',
    'http://change.allowed.com',
]

CSRF_TRUSTED_ORIGINS = [
    'change.allowed.com',
]

CORS_REPLACE_HTTPS_REFERER

CSRF_TRUSTED_ORIGINS was introduced in Django 1.9, so users of earlier versions will need an alternate solution. If CORS_REPLACE_HTTPS_REFERER is True, CorsMiddleware will change the Referer header to something that will pass Django's CSRF checks whenever the CORS checks pass. Defaults to False.

Note that unlike CSRF_TRUSTED_ORIGINS, this setting does not allow you to distinguish between domains that are trusted to read resources by CORS and domains that are trusted to change resources by avoiding CSRF protection.

With this feature enabled you should also add corsheaders.middleware.CorsPostCsrfMiddleware after django.middleware.csrf.CsrfViewMiddleware in your MIDDLEWARE_CLASSES to undo the Referer replacement:

MIDDLEWARE_CLASSES = [
    ...
    'corsheaders.middleware.CorsMiddleware',
    ...
    'django.middleware.csrf.CsrfViewMiddleware',
    'corsheaders.middleware.CorsPostCsrfMiddleware',
    ...
]

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, 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:

# 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.host).exists()

check_request_enabled.connect(cors_allow_mysites)

Then connect it at app ready time using a Django AppConfig:

# myapp/__init__.py

default_app_config = 'myapp.apps.MyAppConfig'
# 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:

# 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)
Comments
  • 'Missing scheme or netloc

    'Missing scheme or netloc" for characters in a string

    @dopeboy reports in https://github.com/ottoyiu/django-cors-headers/issues/403#issuecomment-494656909 :

    I'm getting a bit of a strange error. This is with 3.0.1

    This works fine locally:

    CORS_ORIGIN_WHITELIST = ['localhost:3000']
    

    But when on production, when I run a manage.py operation, I get:

    SystemCheckError: System check identified some issues:
    
    ERRORS:
    ?: (corsheaders.E013) Origin '/' in CORS_ORIGIN_WHITELIST is missing scheme or netloc
    ?: (corsheaders.E013) Origin '/' in CORS_ORIGIN_WHITELIST is missing scheme or netloc
    ?: (corsheaders.E013) Origin '0' in CORS_ORIGIN_WHITELIST is missing scheme or netloc
    ?: (corsheaders.E013) Origin '0' in CORS_ORIGIN_WHITELIST is missing scheme or netloc
    ?: (corsheaders.E013) Origin '0' in CORS_ORIGIN_WHITELIST is missing scheme or netloc
    ?: (corsheaders.E013) Origin '3' in CORS_ORIGIN_WHITELIST is missing scheme or netloc
    ?: (corsheaders.E013) Origin ':' in CORS_ORIGIN_WHITELIST is missing scheme or netloc
    ?: (corsheaders.E013) Origin ':' in CORS_ORIGIN_WHITELIST is missing scheme or netloc
    ?: (corsheaders.E013) Origin 'a' in CORS_ORIGIN_WHITELIST is missing scheme or netloc
    ?: (corsheaders.E013) Origin 'c' in CORS_ORIGIN_WHITELIST is missing scheme or netloc
    ?: (corsheaders.E013) Origin 'h' in CORS_ORIGIN_WHITELIST is missing scheme or netloc
    ?: (corsheaders.E013) Origin 'h' in CORS_ORIGIN_WHITELIST is missing scheme or netloc
    ?: (corsheaders.E013) Origin 'l' in CORS_ORIGIN_WHITELIST is missing scheme or netloc
    ?: (corsheaders.E013) Origin 'l' in CORS_ORIGIN_WHITELIST is missing scheme or netloc
    ?: (corsheaders.E013) Origin 'o' in CORS_ORIGIN_WHITELIST is missing scheme or netloc
    ?: (corsheaders.E013) Origin 'o' in CORS_ORIGIN_WHITELIST is missing scheme or netloc
    ?: (corsheaders.E013) Origin 'p' in CORS_ORIGIN_WHITELIST is missing scheme or netloc
    ?: (corsheaders.E013) Origin 's' in CORS_ORIGIN_WHITELIST is missing scheme or netloc
    ?: (corsheaders.E013) Origin 't' in CORS_ORIGIN_WHITELIST is missing scheme or netloc
    ?: (corsheaders.E013) Origin 't' in CORS_ORIGIN_WHITELIST is missing scheme or netloc
    ?: (corsheaders.E013) Origin 't' in CORS_ORIGIN_WHITELIST is missing scheme or netloc
    

    This doesn't work locally:

    CORS_ORIGIN_WHITELIST = ['http://localhost:3000']
    
    opened by adamchainz 18
  • CORS_ORIGIN_WHITELIST is missing scheme or netloc

    CORS_ORIGIN_WHITELIST is missing scheme or netloc

    CORS version: 3.0 OS: Ubuntu 16.04 LTS Django: 2.2.1

    As soon as I started the server this error occurred:

    django.core.management.base.SystemCheckError: SystemCheckError: System check identified some issues:
    
    ERRORS:
    ?: (corsheaders.E013) Origin 'localhost:3000' in CORS_ORIGIN_WHITELIST is missing scheme or netloc
    ?: (corsheaders.E013) Origin 'localhost:8000' in CORS_ORIGIN_WHITELIST is missing scheme or netloc
    ?: (corsheaders.E013) Origin 'localhost:8080' in CORS_ORIGIN_WHITELIST is missing scheme or netloc
    
    System check identified 3 issues (0 silenced).
    

    My settings file contains the following settings:

    CORS_ORIGIN_WHITELIST = (
        'localhost:8000',
        'localhost:3000',
        'localhost:8080',
    )
    

    I'm using these exact settings in other apps with no issue on version 2.5.2. If I remove the items from this whitelist the errors go away.

    Any insights appreciated. Thanks.

    opened by mosdevly 15
  • ImportError: cannot import name 'six'

    ImportError: cannot import name 'six'

    django.utils.six has been removed from django development version:

    https://github.com/django/django/commit/41384812efe209c8295a50d78b45e0ffb2992436

    File "/usr/local/lib/python3.6/site-packages/corsheaders/init.py", line 1, in from .checks import check_settings # noqa: F401 File "/usr/local/lib/python3.6/site-packages/corsheaders/checks.py", line 8, in from django.utils import six ImportError: cannot import name 'six'

    opened by ivanprjcts 15
  • 'Access-Control-Allow-Origin' header missing in DRF

    'Access-Control-Allow-Origin' header missing in DRF

    django-cors-headers==2.4.0
    Django==2.1 
    djangorestframework==3.8.2
    
    Deploying
    uWSGI == 2.0.17.1
    Nginx == 1.14.0
    

    I have already add corsheaders, corsheaders.middleware.CorsMiddleware to the top, CORS_ORIGIN_ALLOW_ALL=True in my project settings. But when I sent request to webserver, I couldn't find 'Access-Control-Allow-Origin' in response headers. image

    opened by chesterlyd 15
  • Importing default_headers configures corsheaders

    Importing default_headers configures corsheaders

    Doing from corsheaders.defaults import default_headers seems to initialize corsheaders, and does not allow me to add custom headers, however, if I do not import and just copy the values over, it works. This is most likely due to __init__.py import .checks, which is triggererd when the defaults submodule is being imported.

    opened by Tritlo 14
  • CorsMiddleware is not working in Django 1.10

    CorsMiddleware is not working in Django 1.10

    CorsMiddleware is not working with Django 1.10. If it is inserted into the list of middlewares in settings file, an error occurs such as below.

    Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x110eaa158>
    Traceback (most recent call last):
      File "/Users/adrysn/.pyenv/versions/neumann35/lib/python3.5/site-packages/django/utils/autoreload.py", line 226, in wrapper
        fn(*args, **kwargs)
      File "/Users/adrysn/.pyenv/versions/neumann35/lib/python3.5/site-packages/django/core/management/commands/runserver.py", line 142, in inner_run
        handler = self.get_handler(*args, **options)
      File "/Users/adrysn/.pyenv/versions/neumann35/lib/python3.5/site-packages/django/contrib/staticfiles/management/commands/runserver.py", line 27, in get_handler
        handler = super(Command, self).get_handler(*args, **options)
      File "/Users/adrysn/.pyenv/versions/neumann35/lib/python3.5/site-packages/django/core/management/commands/runserver.py", line 64, in get_handler
        return get_internal_wsgi_application()
      File "/Users/adrysn/.pyenv/versions/neumann35/lib/python3.5/site-packages/django/core/servers/basehttp.py", line 49, in get_internal_wsgi_application
        return import_string(app_path)
      File "/Users/adrysn/.pyenv/versions/neumann35/lib/python3.5/site-packages/django/utils/module_loading.py", line 20, in import_string
        module = import_module(module_path)
      File "/Users/adrysn/.pyenv/versions/3.5.0/lib/python3.5/importlib/__init__.py", line 126, in import_module
        return _bootstrap._gcd_import(name[level:], package, level)
      File "<frozen importlib._bootstrap>", line 986, in _gcd_import
      File "<frozen importlib._bootstrap>", line 969, in _find_and_load
      File "<frozen importlib._bootstrap>", line 958, in _find_and_load_unlocked
      File "<frozen importlib._bootstrap>", line 673, in _load_unlocked
      File "<frozen importlib._bootstrap_external>", line 662, in exec_module
      File "<frozen importlib._bootstrap>", line 222, in _call_with_frames_removed
      File "/Users/adrysn/lablup/neumann/neumann/wsgi.py", line 17, in <module>
        application = get_wsgi_application()
      File "/Users/adrysn/.pyenv/versions/neumann35/lib/python3.5/site-packages/django/core/wsgi.py", line 14, in get_wsgi_application
        return WSGIHandler()
      File "/Users/adrysn/.pyenv/versions/neumann35/lib/python3.5/site-packages/django/core/handlers/wsgi.py", line 153, in __init__
        self.load_middleware()
      File "/Users/adrysn/.pyenv/versions/neumann35/lib/python3.5/site-packages/django/core/handlers/base.py", line 82, in load_middleware
        mw_instance = middleware(handler)
    TypeError: object() takes no parameters
    

    This error is probably due to the changed style of middleware introduced in Django 1.10: https://docs.djangoproject.com/en/1.10/topics/http/middleware/.

    The middleware class should be updated to comply with the new style.

    For the moment, one can replace object to MiddlewareMixin to enable the middleware.

    from django.utils.deprecation import MiddlewareMixin
    
    class CorsPostCsrfMiddleware(MiddlewareMixin):
    ...
    
    class CorsMiddleware(MiddlewareMixin):
    ...
    
    opened by adrysn 14
  • regex for random ngrok.io sites

    regex for random ngrok.io sites

    Sorry about this issue. I am trying to use CORS_ALLOWED_ORIGIN_REGEXES to whitelist any ngrok.io address. The generated ngrok.io address is like this: https://da457438d47.ngrok.io. I tried to use the following regex: r"^https://\w+\.ngrok\.io$", but still getting CORS issues. If I whitelist the site using CORS_ALLOWED_ORIGINS, then it works.

    opened by aasutossh 13
  • No Access-Control-Allow-Origin in response headers ?

    No Access-Control-Allow-Origin in response headers ?

    My settings follow:

    INSTALLED_APPS = [
        'corsheaders',
    ]
    
    MIDDLEWARE = [
        'corsheaders.middleware.CorsMiddleware',  # at the top of all middlewares
    ]
    
    CORS_ALLOW_METHODS = [
        'DELETE',
        'GET',
        'OPTIONS',
        'PATCH',
        'POST',
        'PUT',
    ]
    CORS_ALLOW_HEADERS = [
        'accept',
        'accept-encoding',
        'authorization',
        'content-type',
        'dnt',
        'origin',
        'user-agent',
        'x-csrftoken',
        'x-requested-with'
    ]
    CORS_ORIGIN_ALLOW_ALL = True
    
    

    but I met CORB problem because of the miss of the Access-Control-Allow-Origin

    opened by k8scat 13
  • /api/profile is working but getting CORS issue while accessing /api/profile/2

    /api/profile is working but getting CORS issue while accessing /api/profile/2

    Still getting error for some of urls: Failed to load http://*/api/profile/2: Redirect from 'http:///api/profile/2' to 'http:///api/profile/2' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.

    opened by varun4github 13
  • Django 3.1: Error CORS No 'Access-Control-Allow-Origin' header

    Django 3.1: Error CORS No 'Access-Control-Allow-Origin' header

    I use API to connect FE vueJS to BE django but it not response image

    I added the django cors header to the django setting, or CORS_ORIGIN_ALLOW_ALL = True but it still fails. I also wrote a middleware but it still failed image image

    opened by rayzpham 12
  • CORS issue happening randomly

    CORS issue happening randomly

    I use django-cors-headers in my application running locally. My frontend is a React App and it communicates with the django backend via REST API.

    The problem here is that I get CORS error on preflight requests been sent to my backend server. When I retry the request or refresh my browser with "disable cache" option ON, all the API requests will get succeeded.

    Access-Control-Max-Age is set to default value 86400

    The issue is also noticed in the production environment. How do I fix this?

    my settings.py

    CORS_ORIGIN_ALLOW_ALL = True CORS_ALLOW_CREDENTIALS = True

    MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', ..... ]

    opened by OmPrakash95 12
  • Added default_auto_field variable to CorsHeader AppConfig

    Added default_auto_field variable to CorsHeader AppConfig

    Added default_auto_field property to CorsHeaderAppConfig.

    Test Environment:

    • Python 3.10.3
    • Django 4.1.5

    I've experience an issue where if django's DEFAULT_AUTO_FIELD is set within django settings.py to use any values other than the default AutoField. This will caused django to try to generate a new migration within the library which is not an intended behavior.

    Erroneous Log (python manage.py makemigrations):

    Migrations for 'corsheaders':
      <PYTHON_SITE_PACKAGES_DIR>/corsheaders/migrations/0002_alter_corsmodel_id.py
        - Alter field id on corsmodel
    
    opened by panteparak 1
  • 'Access-Control-Allow-Origin' response header returning wildcard '*' even though CORS_ALLOW_ALL_ORIGINS = False and CORS_ALLOW_CREDENTIALS = True

    'Access-Control-Allow-Origin' response header returning wildcard '*' even though CORS_ALLOW_ALL_ORIGINS = False and CORS_ALLOW_CREDENTIALS = True

    Understanding CORS

    • [X] I have read the resources.

    Python Version

    3.10

    Django Version

    4.0.1

    Package Version

    3.13.0

    Description

    Hi, I made a React/DRF app and deployed it as 2 separate apps on Heroku. My issue is that I'm getting the following CORS error:

    Access to fetch at 'https://______backend.herokuapp.com/api/login/' from origin 'https://_____frontend.herokuapp.com' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'.

    Response headers in browser:

    Screenshot

    The request options:

    const credentials = btoa(`${data.get('username')}:${data.get('password')}`);
    const requestOptionsSignIn = {
        method: "POST",
        credentials: 'include',
        headers: {
            'Accept': 'application/json, text/plain',
            'Content-Type': 'application/json',
            "Authorization": `Basic ${credentials}`
        },
        body: JSON.stringify({})
    
    }
    

    django-cors-headers settings:

    CORS_ORIGIN_ALLOW_ALL = False
    CORS_ALLOW_CREDENTIALS = True
    CORS_ALLOWED_ORIGINS = ["https://______frontend.herokuapp.com"]
    
    CORS_ALLOW_HEADERS = [
        "accept",
        "accept-encoding",
        "authorization",
        "content-type",
        "dnt",
        "origin",
        "user-agent",
        "x-csrftoken",
        "x-requested-with",
    ]
    
    CORS_ALLOW_METHODS = [
        "DELETE",
        "GET",
        "OPTIONS",
        "PATCH",
        "POST",
        "PUT",
    ]
    

    I have added corsheaders to installed apps and put the middleware above CommonMiddleware.

    opened by StefanIgnjatovic12 2
  • Fail to filter origin if present

    Fail to filter origin if present

    Understanding CORS

    • [X] I have read the resources.

    Python Version

    3.8

    Django Version

    3.1.14

    Package Version

    Current active branch

    Description

    I'm trying to test CORS in my setup but despite setting CORS_ALLOWED_ORIGINS it still passes without a block

    Then I saw this line in code, what does it do? Basically, it seems to check if the origin is equal to null and if the null is available in the list. Is that actually what it was intended to do? Kindly someone checks it keenly and advise.

    https://github.com/adamchainz/django-cors-headers/blob/main/src/corsheaders/middleware.py#L171

    line-171

    My request

    OPTIONS https://mydomain.com/service-atks/ HTTP/1.2
    accept: */*
    accept-encoding: gzip, deflate, br
    accept-language: en-US,en;q=0.9
    content-length: 394
    content-type: application/json;charset=UTF-8
    Sec-Fetch-Mode: cors
    Sec-Fetch-Site: same-origin
    origin: http://evil.com
    sec-fetch-dest: empty
    sec-fetch-mode: cors
    sec-fetch-site: same-origin
    sec-gpc: 1
    user-agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/103.0.5060.53 Safari/537.36
    

    Response:

    
    HTTP/1.1 204 No Content
    Date: Thu, 30 Jun 2022 09:38:22 GMT
    Content-Type: text/html; charset=utf-8
    Connection: close
    X-Frame-Options: DENY
    Vary: Cookie, Origin
    **Access-Control-Allow-Origin: http://evil.com/**
    Access-Control-Allow-Headers: accept, accept-encoding, authorization, content-type, dnt, origin, user-agent, x-csrftoken, x-requested-with
    Access-Control-Allow-Methods: GET, POST, PUT
    Access-Control-Max-Age: 86400
    Strict-Transport-Security: max-age=31536000, max-age=31536000
    X-Content-Type-Options: nosniff
    X-XSS-Protection: 1; mode=block
    Referrer-Policy: same-origin
    CF-Cache-Status: DYNAMIC
    

    My setting

    CORS_ALLOWED_ORIGINS=["mydomain.com", ]
    CORS_ALLOW_CREDENTIALS=False
    
    opened by felixcheruiyot 2
  • Add Private Network Check

    Add Private Network Check

    Google is starting to ship checks for Private Networks[1]. This is causing me to make some adjustments to my site and I figured I'd start down the path of a PR.

    [1] https://developer.chrome.com/blog/private-network-access-preflight/

    opened by issackelly 3
  • Django 3.1: CORS headers not set on error responses?

    Django 3.1: CORS headers not set on error responses?

    Hello, I'm not sure if there's something I'm misunderstanding, but from my experiments, it seems like django-cors-headers is not setting CORS headers on HTTP 4XX error responses, when used with Django 3.1. I know there's been some changes to the way middleware are handled over the years. Is it possible that django-cors-headers needs to be updated to be fully compatible with newer versions?

    As an experiment, I added a process_exception() method to CorsMiddleware, like this:

    def process_exception(self, request, exception):
        return self.process_response(request, exception)
    

    And that seems to have resolved my issue. Is this a sensible way to proceed? If so, I'm happy to put together a formal pull request.

    Thanks for a useful library!

    opened by bjmc 6
Owner
Adam Johnson
🦄 @django technical board member 🇬🇧 @djangolondon co-organizer ✍ AWS/Django/Python Author and Consultant
Adam Johnson
Blog focused on skills enhancement and knowledge sharing. Tech Stack's: Vue.js, Django and Django-Ninja

Blog focused on skills enhancement and knowledge sharing. Tech Stack's: Vue.js, Django and Django-Ninja

Wanderson Fontes 2 Sep 21, 2022
Django-shared-app-isolated-databases-example - Django - Shared App & Isolated Databases

Django - Shared App & Isolated Databases An app that demonstrates the implementa

Ajai Danial 5 Jun 27, 2022
Django URL Shortener is a Django app to to include URL Shortening feature in your Django Project

Django URL Shortener Django URL Shortener is a Django app to to include URL Shortening feature in your Django Project Install this package to your Dja

Rishav Sinha 4 Nov 18, 2021
This is raw connection between redis server and django python app

Django_Redis This repository contains the code for this blogpost. Running the Application Clone the repository git clone https://github.com/xxl4tomxu9

Tom Xu 1 Sep 15, 2022
Django project starter on steroids: quickly create a Django app AND generate source code for data models + REST/GraphQL APIs (the generated code is auto-linted and has 100% test coverage).

Create Django App ?? We're a Django project starter on steroids! One-line command to create a Django app with all the dependencies auto-installed AND

imagine.ai 68 Oct 19, 2022
APIs for a Chat app. Written with Django Rest framework and Django channels.

ChatAPI APIs for a Chat app. Written with Django Rest framework and Django channels. The documentation for the http end points can be found here This

Victor Aderibigbe 18 Sep 9, 2022
Django-Audiofield is a simple app that allows Audio files upload, management and conversion to different audio format (mp3, wav & ogg), which also makes it easy to play audio files into your Django application.

Django-Audiofield Description: Django Audio Management Tools Maintainer: Areski Contributors: list of contributors Django-Audiofield is a simple app t

Areski Belaid 167 Nov 10, 2022
A Django app to initialize Sentry client for your Django applications

Dj_sentry This Django application intialize Sentry SDK to your Django application. How to install You can install this packaging by using: pip install

Gandi 1 Dec 9, 2021
🔥 Campus-Run Django Server🔥

?? Campus-Run Campus-Run is a 3D racing game set on a college campus. Designed this service to comfort university students who are unable to visit the

Youngkwon Kim 1 Feb 8, 2022
Django server-side adapter for Inertia.js

django-inertia Django server-side new adapter for Inertia.js. Getting Started Install the package pip install django-inertia Configure your project A

Samuel Girardin 14 Sep 16, 2022
django-tables2 - An app for creating HTML tables

django-tables2 - An app for creating HTML tables django-tables2 simplifies the task of turning sets of data into HTML tables. It has native support fo

Jan Pieter Waagmeester 1.6k Jan 3, 2023
A simple app that provides django integration for RQ (Redis Queue)

Django-RQ Django integration with RQ, a Redis based Python queuing library. Django-RQ is a simple app that allows you to configure your queues in djan

RQ 1.6k Jan 6, 2023
A Django app for managing robots.txt files following the robots exclusion protocol

Django Robots This is a basic Django application to manage robots.txt files following the robots exclusion protocol, complementing the Django Sitemap

Jazzband 406 Dec 26, 2022
Yet another Django audit log app, hopefully the simplest one.

django-easy-audit Yet another Django audit log app, hopefully the easiest one. This app allows you to keep track of every action taken by your users.

Natán 510 Jan 2, 2023
A Django app to accept payments from various payment processors via Pluggable backends.

Django-Merchant Django-Merchant is a django application that enables you to use multiple payment processors from a single API. Gateways Following gate

Agiliq 997 Dec 24, 2022
A calendaring app for Django. It is now stable, Please feel free to use it now. Active development has been taken over by bartekgorny.

Django-schedule A calendaring/scheduling application, featuring: one-time and recurring events calendar exceptions (occurrences changed or cancelled)

Tony Hauber 814 Dec 26, 2022
Django app for building dashboards using raw SQL queries

django-sql-dashboard Django app for building dashboards using raw SQL queries Brings a useful subset of Datasette to Django. Currently only works with

Simon Willison 383 Jan 6, 2023
This is a Django app that uses numerous Google APIs such as reCAPTURE, maps and waypoints

Django project that uses Googles APIs to auto populate fields, display maps and routes for multiple waypoints

Bobby Stearman 57 Dec 3, 2022
The best way to have DRY Django forms. The app provides a tag and filter that lets you quickly render forms in a div format while providing an enormous amount of capability to configure and control the rendered HTML.

django-crispy-forms The best way to have Django DRY forms. Build programmatic reusable layouts out of components, having full control of the rendered

null 4.6k Jan 7, 2023