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/codecov/c/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 settings 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:

    Migrations for 'corsheaders':
      <PYTHON_SITE_PACKAGES_DIR>/corsheaders/migrations/0002_alter_corsmodel_id.py
        - Alter field id on corsmodel
    
    opened by panteparak 0
  • '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
Django Ninja is a web framework for building APIs with Django and Python 3.6+ type hints.

?? Fast, Async-ready, Openapi, type hints based framework for building APIs

Vitaliy Kucheryaviy 3.8k Jan 4, 2023
Country-specific Django helpers, to use in Django Rest Framework

django-rest-localflavor Country-specific serializers fields, to Django Rest Framework Documentation (soon) The full documentation is at https://django

Gilson Filho 19 Aug 30, 2022
Async Python 3.6+ web server/framework | Build fast. Run fast.

Sanic | Build fast. Run fast. Build Docs Package Support Stats Sanic is a Python 3.6+ web server and web framework that's written to go fast. It allow

Sanic Community Organization 16.7k Dec 28, 2022
a web-remote minecraft server wrapper with some unique features

Canceled here, continued as Semoxy MCWeb - a Minecraft Server Web Interface MCWeb is a web-remote Minecraft Server Wrapper for controlling your Minecr

Anton Vogelsang 1 Jul 12, 2021
The no-nonsense, minimalist REST and app backend framework for Python developers, with a focus on reliability, correctness, and performance at scale.

The Falcon Web Framework Falcon is a reliable, high-performance Python web framework for building large-scale app backends and microservices. It encou

Falconry 9k Jan 3, 2023
Web APIs for Django. 🎸

Django REST framework Awesome web-browsable Web APIs. Full documentation for the project is available at https://www.django-rest-framework.org/. Fundi

Encode 24.7k Jan 4, 2023
Authentication for Django Rest Framework

Dj-Rest-Auth Drop-in API endpoints for handling authentication securely in Django Rest Framework. Works especially well with SPAs (e.g React, Vue, Ang

Michael 1.1k Dec 28, 2022
Authentication Module for django rest auth

django-rest-knox Authentication Module for django rest auth Knox provides easy to use authentication for Django REST Framework The aim is to allow for

James McMahon 873 Dec 30, 2022
REST implementation of Django authentication system.

djoser REST implementation of Django authentication system. djoser library provides a set of Django Rest Framework views to handle basic actions such

Sunscrapers 2.2k Jan 1, 2023
Django queries

Djaq Djaq - pronounced “Jack” - provides an instant remote API to your Django models data with a powerful query language. No server-side code beyond t

Paul Wolf 53 Dec 12, 2022
A JSON Web Token authentication plugin for the Django REST Framework.

Simple JWT Abstract Simple JWT is a JSON Web Token authentication plugin for the Django REST Framework. For full documentation, visit django-rest-fram

Jazzband 3.3k Jan 4, 2023
Transparently use webpack with django

Looking for maintainers This repository is unmaintained as I don't have any free time to dedicate to this effort. If you or your organisation are heav

null 2.4k Dec 24, 2022
Automated generation of real Swagger/OpenAPI 2.0 schemas from Django REST Framework code.

drf-yasg - Yet another Swagger generator Generate real Swagger/OpenAPI 2.0 specifications from a Django Rest Framework API. Compatible with Django Res

Cristi Vîjdea 3k Jan 6, 2023
Integrate GraphQL into your Django project.

Graphene-Django A Django integration for Graphene. ?? Join the community on Slack Documentation Visit the documentation to get started! Quickstart For

GraphQL Python 4k Dec 31, 2022
Creating delicious APIs for Django apps since 2010.

django-tastypie Creating delicious APIs for Django apps since 2010. Currently in beta but being used actively in production on several sites. Requirem

null 3.8k Dec 30, 2022
Django REST API with React BoilerPlate

This is a setup of Authentication and Registration Integrated with React.js inside the Django Templates for web apps

Faisal Nazik 91 Dec 30, 2022
Introduction to Django Rest Framework

Introduction to Django Rest Framework This is the repository of the video series Introduction to Django Rest Framework published on YouTube. It is a s

Simple is Better Than Complex 20 Jul 14, 2022
Scaffold django rest apis like a champion 🚀

scaffold django rest apis like a champion ??

Abdenasser Elidrissi 133 Jan 5, 2023