1. Same-Origin Policy
The same-origin policy is the cornerstone of browser security.
The definition of same-origin covers three aspects:
- Same protocol
- Same domain
- Same port
Scope of the restrictions:
- Cookie, LocalStorage, and IndexDB cannot be read
- The DOM cannot be obtained
- AJAX requests cannot be sent
Simply put, two URLs whose protocol, domain, and port differ in any way are not allowed to communicate with each other, and the scope covers reading each other’s cookies and DOM and sending AJAX requests.
2. Cross-Origin Communication
- Sharing cookies. When the top-level domain is the same but the subdomains differ, cookies can be shared to achieve cross-origin access.
- Fragment identifier. In http://x.com/x.html#data, the data after the URL’s # is the fragment identifier; an iframe can obtain the data, thereby achieving cross-origin access.
- window.name. Regardless of whether they are same-origin, as long as they are in the same window, if the previous page sets window.name, the next page can read it.
- window.postMessage. A cross-document messaging API that allows communication across windows, whether or not the two windows are same-origin.
3. AJAX
- JSONP
The page adds a script element and requests JSON data from the server; after receiving the request, the server places the data in a designated callback function. However, it can only send GET requests. - WebSocket
WebSocket is a communication protocol that uses ws:// (unencrypted) and wss:// (encrypted) as protocol prefixes. This protocol does not enforce the same-origin policy, because the Origin field can set the request source. - CORS
CORS requires support from both the browser and the server, and CORS communication is no different from same-origin AJAX communication.
Once the browser detects that an AJAX request is cross-origin, it automatically adds some additional header information.
The server side needs to set (1) Access-Control-Allow-Origin, the allowed origin; (2) Access-Control-Allow-Credentials, whether to send cookies and HTTP authentication information; (3) Access-Control-Expose-Headers, the response headers that scripts are allowed to access.
4. django-cors-headers
Install
| |
settings.py configuration
| |
For more detailed configuration, see the project homepage, Go
