Django add cross domain header

django add cross domain header

1, Introduction

1. What is cross domain

When a browser requests the resources of another domain name from the web page of one domain name, the domain name, port and protocol are all cross domain

2. Browser homology policy

The same origin policy limits how documents or scripts loaded from the same source interact with resources from another source. This is an important security mechanism for isolating potentially malicious files

3. Definition of homology

If the protocol, port (if specified) and host of the two pages are the same, the two pages have the same source. We can also call it "protocol / host / port tuple", or simply "tuple". ("tuple" and "Yuan" refer to the combination of some things to form a whole, for example, (1, 2) is binary, (1, 2, 3) is ternary)

The following table shows the relative http://store.company.com/dir/page.html Examples of homology detection:

URLresultreason
http://store.company.com/dir2/other.html success Only the paths are different
http://store.company.com/dir/inner/another.html success Only the paths are different
https://store.company.com/secure.html fail Different protocols (https and http)
http://store.company.com:81/dir/etc.html fail Different ports (http:// 80 is the default)
http://news.company.com/dir/other.html fail Different domain names (news and store)

4. How to allow cross source access

Use CORS Allow cross source access

5. How to block cross source access

  • To prevent cross domain write operations, just detect an undetectable token (CSRF token) in the request, which is called Cross-Site Request Forgery (CSRF) Mark. This flag must be used to prevent cross site reading of the page.
  • To prevent cross site reading of resources, you need to ensure that the resources are not embeddable. Blocking embedding behavior is necessary because embedded resources usually expose information to them.
  • To prevent cross site embedding, you need to ensure that your resources cannot be in the embeddable resource format listed above. In most cases, the browser will not comply with the content type header. For example, if you specify a < script > tag in an HTML document, the browser will try to parse HTML into JavaScript. You can also use CSRF tokens to prevent embedding when your resources are not the entry point of your website.

2, Use

1. Pass django Add cross domain header through Middleware

Create middleware file core py

from django.middleware.common import CommonMiddleware

class MiddlewareMixin:
    def __init__(self, get_response=None):
        self.get_response = get_response
        super().__init__()

    def __call__(self, request):
        response = None
        if hasattr(self, 'process_request'):
            response = self.process_request(request)
        response = response or self.get_response(request)
        if hasattr(self, 'process_response'):
            response = self.process_response(request, response)
        return response


class CORSMiddleware(MiddlewareMixin):

    def process_response(self, request, response):
        # Add response header
        response["Access-Control-Allow-Origin"] = "*"

        # Content type request headers are allowed
        # response["Access-Control-Allow-Headers"] = "Content-Type"

        # Methods to allow requests
        # response["Access-Control-Allow-Methods"] = "DELETE,PUT,POST"

        return response

settings.py add Middleware

MIDDLEWARE = [
    .......
    "app_name.cors.CORSMiddleware",
]

 

By adding middleware, when the current end sends a request (GET, POST) through ajax, the front end can receive the data returned by the api.

 

Article reference https://developer.mozilla.org/zh-CN/docs/Web/Security/Same-origin_policy

Reproduced at: https://www.cnblogs.com/ttyypjt/p/10999449.html

Keywords: Django

Added by ranjita on Thu, 06 Jan 2022 02:49:52 +0200