22 Django advanced - cross domain problems

A homologous strategy

The Same origin policy is a convention. It is the core and basic security function of the browser. If the Same origin policy is missing, the normal functions of the browser may be affected. It can be said that the Web is built on the basis of homology strategy, and the browser is only an implementation of homology strategy

The requested url address must be in the same domain as the url address on the browser, that is, the domain name, port and protocol

For example, my local domain name is 127.0.0.1:8000, and I request another domain name: 127.0.0.1:8001

An error will be reported on the browser. One is the protection of the homology policy. If the browser does not protect javascript from the homology policy, some important confidential websites will be very dangerous

Cross source request intercepted: the same origin policy prohibits reading at http://127.0.0.1: remote resources for 8001 / sendajax /. (reason: CORS header is missing 'access control allow origin').

Note, however, that the access in Item 2 has occurred, indicating that the browser intercepted the results returned by non homologous requests

II. Introduction to CORS (cross domain resource sharing)

CORS requires both browser and server support. At present, all browsers support this function, and IE browser cannot be lower than IE10.

The whole CORS communication process is completed automatically by the browser without user participation. For developers, CORS communication is no different from the same source AJAX communication, and the code is exactly the same. Once the browser finds that AJAX requests cross the source, it will automatically add some additional header information. Sometimes there will be an additional request, but the user will not feel it.

Therefore, the key to realize CORS communication is the server. As long as the server implements the CORS interface, it can communicate across sources.

III. basic process of CORS

The browser divides CORS requests into two categories: simple request and not so simple request.
When the browser sends a CORS simple request, it only needs to add an Origin field in the header information.
When the browser sends a CORS non simple request, it will add an HTTP query request before formal communication, which is called "preflight". The browser first asks the server whether the domain name of the current web page is in the license list of the server, and what HTTP verbs and header information fields can be used. Only when you get a positive reply will the browser send a formal XMLHttpRequest request, otherwise an error will be reported.

IV. detailed explanation of CORS two requests

As long as the following two conditions are met at the same time, it is a simple request.

(1) The request method is one of the following three methods:
HEAD
GET
POST
(2)HTTP The header information of does not exceed the following fields:
Accept
Accept-Language
Content-Language
Last-Event-ID
Content-Type: Limited to three values application/x-www-form-urlencoded,multipart/form-data,text/plain

If the above two conditions are not met at the same time, it is a non simple request.

The browser handles these two requests differently.

* What is the difference between simple requests and non simple requests?

   Simple request: one request
   Non simple request: two requests. Before sending data, one request will be sent for "pre check". Only after the "pre check" passes, another request will be sent for data transmission.
* About "pre inspection"

- Request method: OPTIONS
- "Pre check is actually a check. If the check passes, data can be transmitted. If the check fails, the message you really want to send will not be sent
- How to "pre check"
     => If the complex request is PUT And other requests, the server needs to set to allow a request, otherwise the "pre check" fails
        Access-Control-Request-Method
     => If a complex request has a request header set, the server needs to set a allowed request header, otherwise the "pre check" fails
        Access-Control-Request-Headers

Support cross domain, simple request

Server setting response header: access control allow origin = 'domain name' or '*'

Support cross domain and complex requests

For complex requests, a "pre check" request will be sent first. If the "pre check" is successful, the real data will be sent.

  • When the "pre check" request is allowed, the server needs to set the response header: access control request method
  • When the "pre check" request is allowed, the server needs to set the response header: access control request headers

V. supporting CORS in Django project

Add permission information (simple request) to the returned result

def test(request):
    import json
    obj=HttpResponse(json.dumps({'name':'lqz'}))
    # obj['Access-Control-Allow-Origin']='*'
    obj['Access-Control-Allow-Origin']='http://127.0.0.1:8004'
    return obj

Put it into middleware to handle complex and simple requests:

from django.utils.deprecation import MiddlewareMixin
class CorsMiddleWare(MiddlewareMixin):
    def process_response(self,request,response):
        if request.method=="OPTIONS":
            #Can add*
            response["Access-Control-Allow-Headers"]="Content-Type"
        response["Access-Control-Allow-Origin"] = "http://localhost:8080"
        return response

Posted on Sat, 04 Dec 2021 23:10:53 -0500 by B34ST