The introduction

The Same Origin policy is a convention that restricts how documents or scripts loaded from the Same source can interact with resources from another source. It is the most core and basic security function of a browser. Without the Same origin policy, a browser is vulnerable to XSS and CSFR attacks. This article introduces two common cross-domain solutions, JSONP and CORS, as well as approaches to cross-domain solutions in ThinkJS.

What is homology

If the protocol, port, and domain name of two pages are the same, the two pages have the same source. The following table shows the relative homology detection example: http://store.company.com/dir/page.html

Homology detection table, data from MDN

Non-same-origin requests are called cross-domain requests. In Chrome, if the server does not support cross-domain requests, the following error occurs:


If the domain name is not in the list allowed by the server, the following error occurs:


Two cross-domain solutions

The principle of the json

To understand how this pattern works, I prepared an API that returns the following JSON data.

{" errno ": 0," errmsg ":" ", "data" : [{" id ": 1," name ":" pool "}, {" id ": 2," name ":" lee Christmas "}]}Copy the code

If you set the SRC attribute of the <script> element to this API, you can get JSON data. However, the JavaScript engine cannot parse JSON data, so the API must return executable JavaScript. With JSONP, we add a callback function globally, jsonpCallback, and the browser sends the request with the name of the added callback function as part of the query parameters.

<script type="text/javascript" src="http://localhost:8360/index/users? jsonp=jsonpCallback"> </script>Copy the code

The server populates the JSON data into the jsonpCallback function before passing it to the browser, where the browser gets a JavaScript script, as shown in the following example:

JsonpCallback ({" errno ": 0," errmsg ":" ", "data" : [{" id ": 1," name ":" pool "}, {" id ": 2," name ":" lee Christmas "}]})Copy the code

The principle of CORS

CORS adds fields in the request header and response header, and the server determines whether the domain name can be used for cross-domain communication with the server through the request header. If it can be used for cross-domain communication, the request will carry the Origin header information field in the subsequent communication process. The server’s response will also have an Access-Control-Allow-Origin header field.

CORS requires both browser and server support. The entire CORS communication process is completed automatically by the browser without user participation. For developers, CORS communication is no different from same-origin AJAX communication, and the code is exactly the same. As soon as the browser discovers that an AJAX request crosses the source, it automatically adds some additional headers, and sometimes an additional request, but the user doesn’t feel it.

For details, please refer to Teacher Ruan Yifeng’s blog: Cross-domain resource Sharing CORS details – Ruan Yifeng’s network log

Compare JSONP and CORS

JSONP only supports GET requests for data, and CORS can support multiple request Methods by configuring ‘access-Control-allow-methods’.

JSONP has security issues, CORS is more secure.

Crude JSONP deployments are vulnerable to cross-site request forgery (CSRF/XSRF). Because HTML <script> tags do not comply with the same origin policy in browsers, malicious web pages can request and retrieve JSON data belonging to other sites. This situation allows the malicious site to manipulate the JSON data in the context of the malicious site while the user is logging into that other site, potentially revealing the user’s password or other sensitive data.





This is only a problem if the JSON data contains secret data that should not be exposed to third parties, and the server only relies on the browser’s same-origin policy to block abnormal requests. There is no problem if the server decides on the exclusivity required and outputs data only when the requirements are normal. Cookies alone are not enough to determine that a request is legitimate, which is vulnerable to cross-site request forgery attacks.





Via:
zh.wikipedia.org/wiki/JSONP

JSONP support is better than CORS, so consider using JSONP on older browsers and CORS on older browsers.



Use ThinkJS for cross-domain solutions

Using json

JsonpCallbackField in SRC /config/config.js specifies which field in the query parameter to get the callback function name from.

// default config
module.exports = {
  workers: 1,
  jsonpCallbackField: 'jsonp'
};
Copy the code

JSONP requests are responded to in the controller

const Base = require('.. /base'); Module. Exports = class extends Base {async test2Action() {const users = [{id: 1, name: 'pool'}, {id: 2, name: 'pool'}, {id: 2, name: 'Christmas'}]; If (this.isjsonp ()) {return this.jsonp(users); // The MIME type of the response body is application/javascript} return this.success(users); // The response body MIME type is application/json}}Copy the code

Using CORS

ThinkJS 3 is based on Koa. Some of Koa’s middleware can be used directly in ThinkJS 3, see ThinkJS /think-awesome for details.

Install @koA/CORS middleware and add the configuration to SRC /config/middleware.js as follows:

const cors = require('@koa/cors');
module.exports = [
  {
    handle: 'meta',
    options: {
      logRequest: isDev,
      sendResponseTime: isDev
    }
  },
  {
    handle: cors
  },
  // ...
]
Copy the code

This is the simplest configuration of CORS. See koAJS/CORS for the configuration documentation. Send cross-domain requests after the configuration, as shown in the following figure.


The last

Welcome to use ThinkJS development actively contribute, what SAO operation can show you.