Set up different CORS rules based on the endpoint in Django

Viewed 838

I'm trying to figure out a way to have different CORS rules based on the backend endpoint frontend would hit.

So I can have

/api endpoint with a CORS domain whitelist and

/public-api without a CORS domain whitelist.

This is needed because I have both internal endpoints I use for my own frontend, and a public JS widget that can be installed in any 3rd party domain.

I've looked at django-cors-headers library, but it's regex configuration

CORS_ORIGIN_REGEX_WHITELIST = []

works to let requests FROM a list of domains through.

In my case, I need to a way to have a regex (or another method) to let requests TO my endpoints through or not.

2 Answers

django-cors-headers allows you to specify a custom handler function that will check if the request should be allowed. In your case you can use something like this:

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

def cors_allow_particular_urls(sender, request, **kwargs):
    return request.path.startswith('/public-api/')

check_request_enabled.connect(cors_allow_mysites)

handlers.py needs to be loaded in app config:

# 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

More info here: https://github.com/adamchainz/django-cors-headers#signals

Related