background

Before we get to the body of the story, let’s take a look at the history of the Web and get a sense of how web security has evolved.

In 1989, Sir Tim Berners-Lee designed the first browser and launched the first Web server, Info.cern. ch. The browser back then was a very simple idea, knowledge sharing, and you could type in the right url and get the content.

With the development of The Times, the function of the browser is more and more powerful, from the beginning can only read documents, to the later can view pictures, audio and so on, the Internet is no longer just used for simple browsing document information, check portal sites. At that time, interactive web began to rise, such as user login, purchase goods, all kinds of BBS, etc., as a result it was found that some of the problems, the transmission of the client and the server is using the HTTP protocol, HTTP protocol is stateless, then the server will not know this time request, with the login request before a successful person is not the same person

Due to the stateless nature of the HTTP protocol, the server has forgotten all previous requests, and it cannot determine which client is requested this time, which was successfully logged in earlier.

So cookie came along

Cookie

Cookie is the special information sent by the server to the client, which is stored in the form of text files on the client, and then the client will bring these special information when sending requests to the server for the server to record the status of the client.

While cookie performs its mission, it also has security risks.

Imagine, you log in the banking system, and the login information, account password stored in the cookie, cookie information sharing, everyone’s account and password are also shared, struggling for a lifetime of wealth, others easily transferred away, how terrible it will be. Therefore, in order to maintain Internet privacy and data security, certain rules must be formulated. This is the same origin policy

The same-origin policy

The concept of the same origin policy dates back to the Netscape browser in 1995. As an important security cornerstone, all modern browsers implement the same origin policy to some extent.

Under this policy, web browsers allow scripts on the first page to access data on the second page, but only if both pages have the same source.

The source is a combination of protocol, host name, and port number. This strategy can prevent malicious script on a page by page DOM object to gain access to sensitive information on another page, within the same script can read and write the resources in the domain, * * for resources in other domains, it does not prohibit the execution of the script, but read the HTTP response, * * the security restrictions, called the same-origin policy.

limits

Cookies, LocalStorage, and IndexedDB of non-cognate web pages cannot be read. DOM of non-homologous web pages cannot be accessed. Unable to send AJAX requests to non-same-origin addresses (you can send, but the browser will reject the response)Copy the code

The same origin policy improves the security of the Web front end, but hinders the flexibility of Web extension. ** If static files such as HTML, JS, CSS, Flash and image are all placed on a server, it will increase the pressure on the server and even threaten the availability of Web services. ** Therefore, a balance was chosen between security and availability based on the same origin policy. The following labels are not affected by the same origin policy

* <img src=XXX>
* <link href=XXX>
* <script src=XXX>
* <iframe>
Copy the code

Despite the above supplement to the same origin policy, sometimes we have to access resources in other domains (such as server clusters) so there is a cross-domain solution

Cross-domain solutions

First of all, we need to know the product of the same origin policy of the cross-domain browser, so there is no cross-domain problem on the server side. The call between servers is generally to obtain interface data, with single function. Apps are also relatively free to set their own restrictions such as whitelists.

1. Cross domain (GET request) via JSONP

JSONP is short for JSON with Padding. It is an unofficial protocol that uses

Obviously, JSONP is not a good cross-domain solution, and it has at least two serious problems:

  1. It requires server-side support, but in the non-cross-domain case, the server needs to respond to a normal JSON format
  2. You can only send get requests,scriptThe request made by the element can only begetrequest

2. CORS is cross-domain

CORS is a cross-domain solution based on HTTP1.1, its full name is cross-Origin Resource Sharing, cross-domain Resource Sharing. It is also one of the most widely used solutions.

The general idea is that if the browser wants to access the server’s resources across domains, it needs permission from the server

As you know, a request can be attached with a lot of information, which will cause different degrees of impact on the server. For example, some requests just get some news, and some requests will change the data of the server. For different requests, CORS defines three different interaction modes, which are respectively:

  • A simple request

The request method is get Post head

The request only contains these fields Accept, Accept-language, Content-language, content-Type, DPR, Downlink, save-data, viewport-width, Width

The request header content-type contains only text/plaiin, multipart/form-data, application/ X-www-form-urlencoded

  • Requests for pre-check

  • Request with id card

When a browser determines that an Ajax cross-domain request is a simple request, the following happens

  1. It is added automatically in the request headerOriginfield

  2. Should be contained in the server response headerAccess-Control-Allow-Origin

Judge it as a pre-check request

  1. The browser sends a precheck request asking the server if it will allow it

    OPTIONS/API /user HTTP/1.1 Host: crossdomain.com… Origin: my.com Access-Control-Request-Method: POST Access-Control-Request-Headers: a, b, content-type

2. The server permits

HTTP/1.1 200 OK Date: Tue, 21 Apr 2020 08:03:35 GMT... Access-Control-Allow-Origin: http://my.com Access-Control-Allow-Methods: POST Access-Control-Allow-Headers: a, b, content-type Access-Control-Max-Age: 86400 ...Copy the code

3. The browser sends a real request

  1. The server completes the actual response

Judged to be an attached identity check request

// xhr
var xhr = new XMLHttpRequest();
xhr.withCredentials = true;

// fetch api
fetch(url, {
  credentials: "include"
})
Copy the code

When a request requires a cookie attached, whether it is a simple request or a prechecked request, a cookie field is added to the request header

When the server responds, the client needs to be explicitly told that the server allows such credentials

The notification method is very simple: add access-Control-allow-credentials: true to the response header

For a request with credentials, if the server does not explicitly tell it, the browser will still consider it cross-domain rejected.

Note also that the server must not set access-Control-allow-Origin to * for requests with credentials

3, document.domain + iframe cross domain (same primary domain, different subdomain, set document.domain as base primary domain)

4, location.hash + iframe cross-domain (use the location.hash of iframe to transfer values between different domains)

5, window.name + iframe cross domain (name value [2MB] still exists after different page loads)

6. PostMessage across domains (cross-document communication)

7. Cross-domain Resource Sharing (CORS) (W3C standard, fundamental solution for Cross-source Ajax requests)

Nodejs middleware proxy across domains (server to server requests)

9. The nginx proxy is cross-domain (similar to the Node intermediate key, which uses a forwarding Nginx server to forward requests)

10. WebSocket protocol cross domain (using bidirectional communication protocol)