One: What is the same-origin policy
The same origin policy is a very important security policy implemented in browsers for security purposes.
Same-origin: A URL consists of the protocol, domain name, port, and path. If the protocol, domain name, and port of two urls are the same, they are of the same origin.
Same origin policy: The browser’s same origin policy, which restricts “document” or scripts from different sources from reading or setting certain properties on the current “document”. Scripts loaded from one domain do not allow access to document properties in another domain.
In browsers, tags such as
Two: Ajax across domains
Ajax requests are restricted by the same origin policy. Ajax can interact with remote servers through XMLHttpRequest. In addition, XMLHttpRequest is a pure Javascript object. This interaction process is carried out in the background, and the user is not aware of it. Thus, XMLHTTP actually breaks through the security limitations of Javascript.
For example, suppose a web site references javascript from other sites, and that site has been compromised by a compromise that takes user input and submits it to other sites via Ajax, so that information can be collected continuously.
Or if a site has a bug that causes XSS to inject javascript, the script can retrieve user information through Ajax and submit it to other sites through Ajax, so that information can be collected continuously.
If we want to take advantage of XMLHTTP’s refreshing asynchronous interaction capabilities, but don’t want to overtly violate Javascript security policies, the alternative is to impose a strict same-origin limit on XMLHTTP.
This security policy is similar to the Applet security policy. The limitations of IFrame are limited only to the inability to access data in cross-domain HTMLDOM, while XMLHTTP fundamentally restricts the submission of cross-domain requests. (In fact, CORS has been relaxed as mentioned below.) With the development of Ajax technologies and web services, the need to cross domains has become stronger. The following introduces cross-domain techniques for Ajax.
1, the json
JSONP technology has nothing to do with Ajax. We know that the <script> tag can load javascript scripts that cross domains and belong to the same domain as the current document. Therefore, data and functions in the script can be called/accessed from within the document. If the data in a javascript script is dynamically generated, you can interact with the server’s data by dynamically creating <script> tags in the document.
JSONP uses the cross-domain capability of
How it works: Js introduced through script tags are not restricted by the same origin policy, and XmlHttpRequest objects are affected by the same origin policy, and can load scripts on cross-domain servers. JSONP is not used to obtain JSON data, but can directly run JavaScript statements.
Jsonp takes two arguments: a callback function and data. The callback function is the function that is called to be placed on the current page when the response arrives. The data is the JSON data passed into the callback function, which is the argument to the callback function.
A. JSONP cross-domain invocation using $. Ajax integrated with jQuery
In the following example, we put the JavaScript code for the request page on server 3000 as:
1 // Callback function 2function jsonpCallback(data) {
3 console.log("jsonpCallback: " + data.name)
4 }
5 $("#submit").click(function() {
6 var data = {
7 name: $("#name").val(),
8 id: $("#id").val()
9 };
10 $.ajax({
11 url: 'http://localhost:3001/ajax/deal',
12 data: data,
13 dataType: 'jsonp',
14 cache: false, 15 timeout: 5000, 16 // What field does the server use to obtain the callback function name? 17 jsonp:'callback'JsonpCallback () {// Specify the name of the local callback function.'jsonpCallback',
20 success: function(data) {
21 console.log("ajax success callback: " + data.name)
22 },
23 error: function(jqXHR, textStatus, errorThrown) {
24 console.log(textStatus + ' '+ errorThrown); 25}} 26); 27});Copy the code
The corresponding handler function on server 3001 is:
1 app.get('/ajax/deal'.function(req, res) {
2 console.log("server accept: ", req.query.name, req.query.id)
3 var data = "{" + "name:'" + req.query.name + " - server 3001 process'," + "id:'" + req.query.id + " - server 3001 process'" + "}"4 var jsonp = callback + 5 var jsonp = callback +'(' + data + ') '
6 console.log(jsonp)
7 res.send(jsonp)
8 res.end()
9 })
Copy the code
Parsererror Error: jsonpCallback was not called parserError: jsonpCallback was not called.
B. the use of<script>
Tag native implementation JSONP
After the above events, do you feel that the JSONP implementation is similar to Ajax?
In fact, JSONP has nothing to do with Ajax in terms of implementation principle, because JSONP makes cross-domain calls not through XmlHttpRequset objects, but through script tags. It looks similar only because jQuery encapsulates and transforms JSONP.
For example, in the above example, we assume that the data to be transferred is in the following format:
{
name: "chiaki",
id":"3001"}Copy the code
So how does the data get transmitted? The first line of the HTTP request header reads as follows:
GET /ajax/deal? The callback = jsonpCallback&name = chiaki&id = 3001 & _ = 1473164876032 HTTP / 1.1Copy the code
As you can see, even though it is formally a JSON data transfer using POST, the request is actually converted into a GET request.
If you understand JSONP, it’s easy to understand why you can only use the GET request method. Since the request is made through a script tag, the above transfer process is essentially the following:
<script src = 'http://localhost:3001/ajax/deal? callback=jsonpCallback&name=chiaki&id=3001&_=1473164876032'></script>
Copy the code
This allows the code returned from the server to run directly in the script tag. Let’s implement a JSONP ourselves:
In the JavaScript code of the server 3000 request page, the only callback function is jsonpCallback:
function jsonpCallback(data) {
console.log("jsonpCallback: "+data.name)
}
Copy the code
The server 3000 request page also contains a script tag:
<script src = 'http://localhost:3001/jsonServerResponse? jsonp=jsonpCallback'></script>
Copy the code
The corresponding handler on server 3001:
app.get('/jsonServerResponse'.function(req, res) {var cb = req.query.jsonp console.log(cb) {var data ='var data = {' + 'name: $("#name").val() + " - server 3001 jsonp process",' + 'id: $("#id").val() + " - server 3001 jsonp process"' + '}; '
var debug = 'console.log(data); '// Prints var data="";
var callback = '$("#submit").click(function() {' + data + cb + '(data); ' + debug + '}); 'Res.send (callback) // Returns a button click event res.end()})Copy the code
As above, we add “-server 3001 jSONP process” to the end of the obtained parameter to represent what the server does to the data. From the code, we can see that in addition to processing parameters, the processing function is also a string concatenation.
Json:
- The only way to initiate a request is to use the GET method, which is not secure because
script
The label itself is limited. - Failure to detect errors and deal with them. In contrast to Ajax, event listeners such as SUCCESS and error cannot be registered because they are not transmitted through XmlHttpRequest.
2. Use CORS to achieve cross-domain invocation
How it works: The idea of CORS is to use custom HTTP headers to let the browser communicate with the server to determine whether a request or response should succeed or fail.
Cross-origin Resource Sharing (CORS) is a specification of browser technology that provides a way for Web services to send sandbox scripts from different domains to avoid the browser’s same-origin policy. It is a modern version of the JSONP pattern. Unlike JSONP, CORS supports other HTTP requests in addition to GET request methods. CORS generally uses XMLHttpRequest, which has better error handling than JSONP. JSONP, on the other hand, can run on older browsers that do not support CORS. Modern browsers all support CORS.
CORS serves the same purpose as JSONP, but is more powerful than JSONP.
JSONP supports only GET requests, and CORS supports all types of HTTP requests. JSONP has the advantage of supporting older browsers and being able to request data from sites that do not support CORS.
3, the window name
The name property of the window object is a special property. When the location of the window changes and the window is reloaded, its name property can remain the same. So we can use iframe on page A to load page B from other fields, and page B uses JavaScript to assign data to window.name. After loading the iframe (iframe.onload), page A changes the address of the iframe. Name = window.name = window.name = window.name = window.name = window.name = window.name = window.name = window.name = window.name = window.name = window.name = window.name Instead, get its window.name via iframe. This approach is very suitable for one-way data requests, and the protocol is simple and secure. Do not execute external scripts without restrictions like JSONP does.
4. Proxy Proxy of the server
The data provider does not provide support for JSONP protocol or window.name protocol, nor does it open access rights to other domains, so we can capture data through server proxy. For example, when a page in the Baidu.com domain requests the google.com resource file getusers.php, an Ajax request directed to google.com/getUsers.php will be blocked by the browser. At this time, we set up a proxy under Baidu.com and bind Ajax requests to the proxy path, such as baidu.com/proxy/. Then the proxy sends HTTP requests to google.com’s getusers.php. Cross-domain HTTP requests are made on the server side (which is not restricted by the same origin policy), and the client does not make cross-domain Ajax requests. This cross-domain approach does not require an agreement with the target resource and is aggressive.
5, flash the URLLoader
Flash has its own set of security policies. The server can use the crossdomain. XML file to declare which domain SWF files can be accessed, and SWF can use the API to determine which domain SWF files can be loaded. When cross-domain resources are accessed, for example, data from Google.com is requested from Domain Baidu.com, flash is used to send HTTP requests. First, change the crossdomain. XML on google.com (usually stored in the root directory, if you do not need to manually create) and whitelist baidu.com. Second, the HTTP request is sent through the Flash URLLoader, and finally, the response result is passed to JavaScript through the Flash API. Flash URLLoader is a common cross-domain solution, but it is not feasible if you need iOS support.
Document.domain (between two iframes)
By modifying the Domain property of the Document, we can communicate between domains and subdomains or between different subdomains. The same-domain policy considers that domain and subdomain belong to different domains, for example, Baidu.com and Youxi.baidu.com are different domains. In this case, we cannot call the JavaScript method defined in Youxi.baidu.com in the pages under Baidu.com. But when we change the domain property of their document to baidu.com, the browser will think that they are in the same domain, so we can get each other’s data or manipulate each other’s DOM.
Question:
1, security, when a site is attacked, another site will cause security vulnerabilities.
2. If there are multiple iframes in a page, the same domain must be set for all iframes to be able to operate.
7. Use HTML5 postMessage method (between two iframes or between two pages)
Advanced browsers Internet Explorer 8+, Chrome, Firefox, Opera and Safari will all support this feature. This functionality consists of a “message” event that receives messages and a “postMessage” method that sends messages. For example, the A page of the Baidu.com domain has embedded A PAGE of the GOOGLE.com domain B through iframe. The communication between A and B can be realized in the following ways
A page sends messages using the postMessage method:
window.onload = function() {
var ifr = document.getElementById('ifr');
var targetOrigin = "http://www.google.com";
ifr.contentWindow.postMessage('hello world! ', targetOrigin);
};
Copy the code
How to use postMessage:
otherWindow.postMessage(message, targetOrigin);
OtherWindow: Specifies the target window, that is, the window to which the message is sent, either as a member of the window.frames property or as a window created by the window.open method
Message: indicates the message to be sent. The type of the message is String or Object (Not supported by Internet Explorer 8 and 9).
TargetOrigin: yes limit the range of messages to be received, do not limit please use ‘*’
Page B listens for and receives messages via message events:
var onmessage = function(event) { var data = event.data; Var origin = event.origin; // Message source address varsource= event.source; // Source Window objectif(origin=="http://www.baidu.com"){
console.log(data);//hello world!
}
};
if(typeof window.addEventListener ! ='undefined') {
window.addEventListener('message', onmessage, false);
} else if(typeof window.attachEvent ! ='undefined'{/ /for ie
window.attachEvent('onmessage', onmessage);
}
Copy the code
Three: Cookie same-origin policy
The same origin in cookies only focuses on domain names, ignoring protocols and ports. So the cookies of https://localhost:8080/ and http://localhost:8081/ are shared.