django: corsheaders solve cross-domain problems

created at 07-16-2021 views: 2

background

Front-end and back-end development are separated, and cross-domain problems will inevitably be encountered due to the use of Vue architecture in the front-end development

Solution

Use corsheaders module

steps

corsheaders installation

pip install django-cors-headers

register app

Register the app into the setting.py file in the project

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

Middleware settings

MIDDLEWARE = [  
    ...    
    'corsheaders.middleware.CorsMiddleware',
    ...
]

Add whitelist and other configuration information

CORS_ORIGIN_ALLOW_ALL
Add hosts that are allowed to perform cross-site requests

# If True, the whitelist will not be used, and all sources will be accepted. The default is False. CORS_ORIGIN_ALLOW_ALL = True

CORS_ORIGIN_WHITELIST:
A list of sources authorized to make cross-site HTTP requests. The default is []

CORS_ORIGIN_WHITELIST = [
    '127.0.0.1:8080',
]

CORS_ORIGIN_REGEX_WHITELIST:
Regular expression string list

CORS_ORIGIN_REGEX_WHITELIST = [
    r"^ 
]

CORS_URLS_REGEX:
It is useful when you only need to use CORS on a part of the website, such as the API located at /api/. CORS_URLS_REGEX = r'^/api/.*$'

CORS_URLS_REGEX = [
     r'^/api/.*$',
]

CORS_ALLOW_METHODS:
A list of HTTP verbs allowed for the actual request. (No need to write, not writing will not affect the use)

# default 
# CORS_ALLOW_METHODS = [
#     'DELETE',
#     'GET',
#     'OPTIONS',
#     'PATCH',
#     'POST',
#     'PUT',
# ]

# Customize the list of allowed http verbs
from corsheaders.defaults import default_methods
CORS_ALLOW_METHODS = list(default_methods) + [
    'POKE',]

CORS_ALLOW_HEADERS:
A list of non-standard HTTP headers that can be used when making the actual request.

# default:
# CORS_ALLOW_HEADERS = [
#     'accept',
#     'accept-encoding',
#     'authorization',
#     'content-type',
#     'dnt',
#     'origin',
#     'user-agent',
#     'x-csrftoken',
#     'x-requested-with',]
# Custom http header 
from corsheaders.defaults import default_headers
CORS_ALLOW_HEADERS = list(default_headers) + [
    'my-custom-header',]

CORS_EXPOSE_HEADERS:
A list of HTTP headers that will be exposed to the browser. The default is [].

CORS_PREFLIGHT_MAX_AGE:
The number of seconds that the client/browser can cache the preflight response. If the value is 0 (or any wrong value), the maximum expiration header will not be sent. The default is 86400 (one day).

Note: The preflight request is determined when a "not too simple" request (such as Content-Type, not application/x-www-form-urlencoded) is issued. It is an additional request to determine the request actually accepted by the server.

CORS_ALLOW_CREDENTIALS:
If True, it will allow cookies to be included in cross-site HTTP requests. The default is False

In Django 2.1, the SESSION_COOKIE_SAMESITE setting is added, and'Lax' is set to by default, which will prevent Django's session cookie from being sent across domains. Change it to None to bypass this security restriction

CSRF integration
Most sites need to take advantage of the cross-site request forgery protection provided by Django. CORS and CSRF are separate, and Django cannot use your CORS configuration to exempt the website Referer from checking for security requests. The way to do this is to use its CSRF_TRUSTED_ORIGINS setting. E.g:

CORS_ORIGIN_WHITELIST = [
    '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 alternative solution. If CORS_REPLACE_HTTPS_REFERER is True, CorsMiddleware will change the Referer header to something that will pass Django's CSRF check whenever the CORS check passes. The default is False.

Please note that unlike CSRF_TRUSTED_ORIGINS, this setting does not allow you to distinguish between CORS trusting the domain that reads the resource and avoiding CSRF protection and trusting the domain that changes the resource.

After enabling this function corsheaders.middleware.CorsPostCsrfMiddleware, django.middleware.csrf.CsrfViewMiddleware should also be added afterwards, MIDDLEWARE_CLASSES to undo Referer replacement:

MIDDLEWARE_CLASSES = [
    ...
    'corsheaders.middleware.CorsMiddleware',
    ...
    'django.middleware.csrf.CsrfViewMiddleware',
    'corsheaders.middleware.CorsPostCsrfMiddleware',
    ...
]
Please log in to leave a comment.