Package: django-cors-headers
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 skillswithmy books.About CORSAdding 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 comicandeducational quiz.Jake Archibald’sHow to win at CORSTheMDN ArticleTheHTML5 Rocks TutorialTheWikipedia PageRequirementsPython 3.8 to 3.12 supported.Django 3.2 to 5.0 supported.SetupInstall frompip:python-mpipinstalldjango-cors-headersand then add it to your installed apps:INSTALLED_APPS=[...,"corsheaders",...,]Make sure you add the trailing comma or you might get aModuleNotFoundError(seethis blog
post).You will also need to add a middleware class to listen in on responses:MIDDLEWARE=[...,"corsheaders.middleware.CorsMiddleware","django.middleware.common.CommonMiddleware",...,]CorsMiddlewareshould be placed as high as possible, especially before any
middleware that can generate responses such as Django’sCommonMiddlewareor
Whitenoise’sWhiteNoiseMiddleware. If it is not before, it will not be able
to add the CORS headers to these responses.Aboutdjango-cors-headerswas created in January 2013 by Otto Yiu. It went
unmaintained from August 2015 and was forked in January 2016 to the packagedjango-cors-middlewareby Laville Augustin at Zeste de Savoir.
In September 2016, Adam Johnson, Ed Morley, and others gained maintenance
responsibility fordjango-cors-headers(Issue 110)
from Otto Yiu.
Basically all of the changes in the forkeddjango-cors-middlewarewere
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-headershas had40+ contributorsin its time; thanks to every one of them.ConfigurationConfigure the middleware’s behaviour in your Django settings. You must set at
least one of three following settings:CORS_ALLOWED_ORIGINSCORS_ALLOWED_ORIGIN_REGEXESCORS_ALLOW_ALL_ORIGINSCORS_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 theaccess-control-allow-originheader.
Defaults to[].An Origin is defined bythe CORS RFC Section 3.2as a URI scheme + hostname + port, or one of the special values'null'or'file://'.
Default ports (HTTPS = 443, HTTP = 80) are optional.The special valuenullis sent by the browser in“privacy-sensitive contexts”, such as when the client is running from afile://domain.
The special valuefile://is sent accidentally by some versions of Chrome on Android as perthis 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 calledCORS_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 whenCORS_ALLOWED_ORIGINSis 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 calledCORS_ORIGIN_REGEX_WHITELIST, which still works as an alias, with the new name taking precedence.CORS_ALLOW_ALL_ORIGINS: boolIfTrue, all origins will be allowed.
Other settings restricting allowed origins will be ignored.
Defaults toFalse.Setting this toTruecan bedangerous, as it allows any website to make cross-origin requests to yours.
Generally you’ll want to restrict the list of allowed origins withCORS_ALLOWED_ORIGINSorCORS_ALLOWED_ORIGIN_REGEXES.Previously this setting was calledCORS_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 tor'^.*$', 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: Sequence[str]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 ascorsheaders.defaults.default_methodsso you can just extend it with your custom methods.
This allows you to keep up to date with any future changes.
For example:fromcorsheaders.defaultsimportdefault_methodsCORS_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 theAccess-Control-Allow-Headersheaderin responses topreflight requests.
Defaults to:CORS_ALLOW_HEADERS=("accept","authorization","content-type","user-agent","x-csrftoken","x-requested-with",)The default can be imported ascorsheaders.defaults.default_headersso you can extend it with your custom headers.
This allows you to keep up to date with any future changes.
For example:fromcorsheaders.defaultsimportdefault_headersCORS_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 defaultsafelisted headers.
If non-empty, these are declared in theaccess-control-expose-headersheader.
Defaults to[].CORS_PREFLIGHT_MAX_AGE: intThe number of seconds the browser can cache the preflight response.
This sets theaccess-control-max-ageheaderin preflight responses.
If this is 0 (or any falsey value), no max age header will be sent.
Defaults to86400(one day).Note:Browsers sendpreflight requestsbefore certain “non-simple” requests, to check they will be allowed.
Read more about it in theCORS MDN article.CORS_ALLOW_CREDENTIALS: boolIfTrue, cookies will be allowed to be included in cross-site HTTP requests.
This sets theAccess-Control-Allow-Credentialsheaderin preflight and normal responses.
Defaults toFalse.Note: in Django 2.1 theSESSION_COOKIE_SAMESITEsetting 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.CORS_ALLOW_PRIVATE_NETWORK: boolIfTrue, allow requests from sites on “public” IP to this server on a “private” IP.
In such cases, browsers send an extra CORS headeraccess-control-request-private-network, for whichOPTIONSresponses must containaccess-control-allow-private-network:true.Refer to:Local Network Access, the W3C Community Draft specification.Private Network Access: introducing preflights, a blog post from the Google Chrome team.CSRF IntegrationMost sites will need to take advantage of theCross-Site Request Forgery
protectionthat Django
offers. CORS and CSRF are separate, and Django has no way of using your CORS
configuration to exempt sites from theRefererchecking that it does on
secure requests. The way to do that is with itsCSRF_TRUSTED_ORIGINS setting.
For example:CORS_ALLOWED_ORIGINS=["https://read-only.example.com","https://read-and-write.example.com",]CSRF_TRUSTED_ORIGINS=["https://read-and-write.example.com",]SignalsIf 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 thecheck_request_enabledDjango signal, which
provides therequestargument (use**kwargsin 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.pyfromcorsheaders.signalsimportcheck_request_enabledfrommyapp.modelsimportMySitedefcors_allow_mysites(sender,request,**kwargs):returnMySite.objects.filter(host=request.headers["origin"]).exists()check_request_enabled.connect(cors_allow_mysites)Then connect it at app ready time using aDjango AppConfig:# myapp/__init__.pydefault_app_config="myapp.apps.MyAppConfig"# myapp/apps.pyfromdjango.appsimportAppConfigclassMyAppConfig(AppConfig):name="myapp"defready(self):# Makes sure all signal handlers are connectedfrommyappimporthandlers# noqaA common use case for the signal is to allowallorigins to access a subset
of URL’s, whilst allowing a normal set of origins to accessallURL’s. This
isn’t possible using just the normal configuration, but it can be achieved with
a signal handler.First setCORS_ALLOWED_ORIGINSto the list of trusted origins that are
allowed to access every URL, and then add a handler tocheck_request_enabledto allow CORS regardless of the origin for the
unrestricted URL’s. For example:# myapp/handlers.pyfromcorsheaders.signalsimportcheck_request_enableddefcors_allow_api_to_everyone(sender,request,**kwargs):returnrequest.path.startswith("/api/")check_request_enabled.connect(cors_allow_api_to_everyone)