Several common solutions across domains

Today, I will share with you the knowledge points that may be used in the JS S-5 mission on the official website of the Cultivation Institute:

1. Background introduction

1.1 What is cross domain?

Cross-domain means that a document or script in one domain attempts to request resources in another domain, where cross-domain is broad.


Generalized cross-domain:
1.) Resource jump: A link, redirection, form submission
2.) Resource embedding: DOM tags such as link script img frame, as well as background:url(), @font-face() in style
3.) Script request: Ajax request initiated by js, cross-domain operation of dom and js objects, etc.


In the front-end part, what we usually call cross-domain is a narrow sense, which is a type of request scenario restricted by the browser's same-origin policy.

1.2 So what is the same-origin policy?

Same origin policy/SOP (Same origin policy) is a convention, which was introduced into browsers by Netscape in 1995. It is the core and most basic security function of browsers. Without the same origin policy, browsers are vulnerable to XSS. , CSFR and other attacks. The so-called homology means that "protocol + domain name + port" are the same, even if two different domain names point to the same IP address, they are not homologous.


The same-origin policy restricts the following behaviors: 1.) Cookies, LocalStorage and IndexDB cannot be read 2.) DOM and Js objects cannot be obtained 3.) AJAX requests cannot be sent

1.3 Common cross-domain scenarios


2. Knowledge analysis

2.1 Common cross-domain methods

When JSONP


uses the XMLHTTPRequest object to send HTTP requests, it will encounter the same-origin policy problem, and requests from different domains will be intercepted by browsers. At this time, you can choose to bypass, or not use the XMLHTTPRequest object to send cross-domain HTTP requests. When you usually write html, you will find such as

<script src="http://www.a.com/script/1.js"></script>
<img src="http://www.b.com/1.jpg">
<link href="http://www.c.com/1.css">              
                      
This kind of tag will not encounter the 'cross-domain' problem. Strictly speaking, this is not cross-domain. Cross-domain refers to sending HTTP requests to non-same-origin domains in script code. This is just a cross-site resource request.

Then we can try to use this cross-site resource request method to implement cross-domain HTTP requests

                  <!-- HTML header part-->
                        ...
                        <!-- javaScript fragment 1-->
                        // if jsonp's request is GET
  if ( ctx.method === 'GET' && ctx.url.split('?')[0] === '/getData') {

    // Get the callback of jsonp
    let callbackName = ctx.query.callback || 'callback'
    let returnData = {
      success: true,
      data: {
        text: 'this is a jsonp api',
        time: new Date().getTime(),
      }
    }

    // jsonp's script string
    let jsonpStr = `;${callbackName}(${JSON.stringify(returnData)})`

    // Use text/javascript to make requests support cross-domain fetching
    ctx.type = 'text/javascript'

    // output jsonp string
    ctx.body = jsonpStr

  } else {

    ctx.body = 'hello jsonp'

  }
})
Reverse proxy for NGINX

Nginx supports the configuration of reverse proxy, and realizes load balancing of website through reverse proxy. This part first writes an nginx configuration, and then needs to study the proxy module and load balancing module of nginx in depth. nginx configures proxy sites through proxy_pass_http, and upstream achieves load balancing.


WINDOW.NAME + IFRAME

Fundamentals of the WINDOW.NAME transfer technology:

When a page is opened in the browser, or an iframe is added to the page, a corresponding window object is created. When the page loads another new page, the name property of the window will not change. In this way, you can dynamically add an iframe to the page and then src to load the data page, and assign the required data to window.name on the data page. However, at this time, the parent page that hosts the iframe still cannot be accessed directly. The name attribute of the iframe is not in the same domain. At this time, you only need to load the iframe with a blank page in the same domain as the hosting page, and then you can read the data of window.name

name is a property of the global/window object in the browser environment, and when a new page is loaded in the frame, the value of the name property remains the same. By loading a resource in an iframe, the target page will set the frame's name attribute. The value of this name attribute can be retrieved to access the information sent by the web service. But the name attribute is only accessible to frames of the same domain name. This means that in order to access the name property, the frame must be navigated back to the original domain when the remote Web service page is loaded. The same-origin policy still prevents other frames from accessing the name attribute. Once the name attribute is obtained, destroy the frame.

At the very top level, the name attribute is unsafe, and any information set in the name attribute is available for all subsequent pages. However the windowName module always loads resources in an iframe, and once the data is fetched, or when you browse a new page at the top level, the iframe will be destroyed, so other pages will never have access to the window.name property


<script type="text/javascript">
iframe = document.createElement('iframe');
iframe.style.display = 'none';
var state = 0;
iframe.onload = function() {
if(state === 1) {
var data = JSON.parse(iframe.contentWindow.name);
console.log(data);
iframe.contentWindow.document.write('');
iframe.contentWindow.close();
document.body.removeChild(iframe);
} else if(state === 0) {
state = 1;
iframe.contentWindow.location = 'http://localhost:81/cross-domain/proxy.html';//Point to an empty file in your own root directory
}
};
iframe.src = 'http://localhost:8080/data.php';//Different source data to request
document.body.appendChild(iframe);
</script>

You can also set cors headers on node.js or other servers to authorize cross-domain


3. Frequently Asked Questions


4. Solutions


5. Coding practice


6. Expand your thinking

6.1 Forward proxy



The forward proxy is like a springboard, and the proxy accesses external resources.




 I am a user, I can't access a certain website, but I can access a proxy server, this proxy server, he can access the website that I can't access, so I first connect to the proxy server and tell him that I need the inaccessible website The content, the proxy server goes to get it back, and then returns it to me. From the website's point of view, there is only one record when the proxy server fetches the content. Sometimes it is not known that it is the user's request, and the user's information is also hidden, depending on whether the proxy tells the website or not.

  The client must set the forward proxy server, of course, the premise is to know the IP address of the forward proxy server and the port of the agent program.

In summary: a forward proxy is a server that sits between a client and an origin server. To get content from the origin server, the client sends a request to the proxy specifying the target (origin server), and the proxy sends the The server forwards the request and returns the obtained content to the client. Clients must do some special setup to use forward proxy.   
The purpose of forward proxy:
  (1) Access resources that were previously inaccessible, such as google
(2) Can be cached to speed up access to resources
  (3) Authorize client access and authenticate the Internet

  (4) The agent can record user access records (Internet behavior management) and hide user information from the outside world

6.2 Reverse proxy


The client is unaware of the existence of the proxy. The reverse proxy is transparent to the outside world, and the visitor does not know that he is accessing a proxy. Because the client can access without any configuration.
  The actual operation mode of reverse proxy (Reverse Proxy) refers to the proxy server to accept the connection request on the internet, then forward the request to the server on the internal network, and return the result obtained from the server to the client requesting the connection on the internet At this time, the proxy server behaves as a server to the outside world.
The role of reverse proxy:
(1) To ensure the security of the intranet, reverse proxy can be used to provide WAF function and prevent web attacks

For large websites, the reverse proxy is usually used as the public network access address, and the web server is the intranet.


(2) Load balancing, optimize the load of the website through the reverse proxy server


6.3 The difference between the two


Explain by borrowing the picture of the last soul painter

7. References

Front-end common cross-domain solutions: https://www.cnblogs.com/roam/p/7520433.html 

Detailed explanation of several cross-domain methods used in js: https://www.cnblogs.com/2050/p/3191744.html

8. More discussion

1. Which cross-domain is commonly used?

Taobao, Baidu, Netease Cloud Music, etc. will configure the public API, which will be JSONP

In the company, you will choose window.name or nginx reverse proxy

We will use nginx.conf for reverse proxy in our task

2. In terms of security, it is best to choose the cross-domain method. Why?

Generally, the safest is WINDOW.NAME, because the iframe will be destroyed.

3. Disadvantages of
JSONP jsonp has a defect that it can only get

And it will send the requested content to the url, resulting in extremely low security


Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324647943&siteId=291194637