How to Configure CORS in Django - Communication with multiple Applications
Noah Olatoye

Noah Olatoye

567

How to Configure CORS in Django - Communication with multiple Applications

We can create a rapid application with Django, a Python web framework. In a way, an application that speaks to only itself seems to be a static site to me.

However, to take full advantage of IoT (Internet of Things), how applications need to at least communicate and interact with other applications hosted on different destination domains or perhaps just different ports.

To perform a successful request through multiple applications, you’ll need to use CORS (cross-origin resource sharing) in your server; otherwise, your code will break.

Thanks to the Django community, they made it easy to allow CORS requests and bypass errors. If your goal is to set up an error-free request between applications, be sure you read to the end.

##What is CORS? Why do we even need CORS in the first place? The simple answer is, CORS is an inbuilt browser feature that helps us to block intruders from gaining access to our web application.

The browser (which is the client-side) will only allow a connection with resources hosted on different domains if the server is configured explicitly to do so.

You will often come across CORS blocking when performing Ajax or Axios requests.

Imagine you hosted your website on instincthub.com; let us say whenever you want to login a user; you need to call the API hosted on api.instincthub.com.

So whenever a get or post request is sent to api.instincthub.com, the server evaluates the request based on the header and checks if instincthub.com is allowed; if it is, the server will provide the proper response.

The server will provide an error if instincthub.com is not specified on api.instincthub.com. Often, you will get an unauthorised status (403). This is because the request activity exchanges occur using HTTP headers (Hypertext Transfer Protocol).

##Allowing CORS in Django Django gives a straightforward way to enable CORS. Here are must take steps to get a proper connection.


Install from **pip**: ``` python -m pip install django-cors-headers ```
and then add it to your installed apps: ```python 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).


## Required Settings Required settings tell the module how to evaluate a request's origin. Based on the settings you defined, the module decides if the source is valid to continue processing the request and provide a response.

Depending on your application needs, you can customise the module to authorise requests from specific domains, regular expressions, or all requests. What options you should configure will depend on your back end's purpose. For example, sometimes all origins are valid, but in other cases, you'll need to narrow them to only a few, as shown below.


### CORS_ALLOWED_ORIGINS `CORS_ALLOWED_ORIGINS` is the list of origins authorized to make requests. For example, below I’ve specified four origins:
CORS_ALLOWED_ORIGINS = [
    "https://example.com",
    "https://sub.example.com",
    "http://localhost:8080",
    "http://127.0.0.1:9000",
]

###CORS_ALLOWED_ORIGIN_REGEXES `CORS_ALLOWED_ORIGIN_REGEXES` are regular expressions that match domains that can make requests. This setting is especially useful if you have many domains. ```python CORS_ALLOWED_ORIGIN_REGEXES = [ r"^https://\w+\.example\.com$", ] ```

###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: ```python CORS_URLS_REGEX = r"^/api/.*$" ```
###CORS_ALLOW_HEADERS: Sequence[str] 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",
]

###CORS_ALLOW_METHODS ```python CORS_ALLOW_METHODS = [ "DELETE", "GET", "OPTIONS", "PATCH", "POST", "PUT", ] ```
###CORS_EXPOSE_HEADERS `CORS_EXPOSE_HEADERS` is a list of headers exposed to the browser. The default is an empty array.
###CORS_PREFLIGHT_MAX_AGE The `CORS_PREFLIGHT_MAX_AGE` setting defines the time in seconds a browser can cache a header response to a preflight request. It defaults to 86,400 seconds (one day).
###CORS_ALLOW_CREDENTIALS `CORS_ALLOW_CREDENTIALS` is a true or false value. So, its value determines whether the server allows cookies in the cross-site HTTP requests.

##Conclusion This article shows that CORS is a security feature designed to protect users from malicious websites. Therefore, it makes sense to allow only specific domains to perform CORS requests on our application. Thus, the servers need the proper structure to accept incoming requests from other endpoints.

There is no need to configure this setup if you don't need to accept the external request. And even if you do need it, make sure the configuration is done correctly to avoid being hacked and and avoid unexpected errors.

A tech career with instinctHub

Ready to kickstart your tech career or enhance your existing knowledge? Contact us today for a dedicated instructor experience that will accelerate your learning and empower you to excel in the world of technology.

Our expert instructors are here to guide you every step of the way and help you achieve your goals. Don't miss out on this opportunity to unlock your full potential. Get in touch with us now and embark on an exciting journey towards a successful tech career.

Add Comments

First Name
Last Name
Say something:

Are you human? Solve this:

+ = ?

Post you may also like