An overview of the

define

The Cookie set on web page A cannot be opened on web page B unless the two web pages are “homologous”. “Homology” means “three of the same”.

  • The agreement is the same
  • Domain name is the same
  • The same port

purpose

It is to ensure the security of user information and prevent malicious websites from stealing data.

limits

  • Cookie, LocalStorage, and IndexDB cannot be read.
  • DOM is not available.
  • AJAX requests cannot be sent.

cookie

  1. Access to two pages can be set up by setting the same document.domain with the same level 1 domain name. (Only applicable to cookie and IFrame Windows)
  2. When the server responds, the domain is set to level 1 domain name, level 2 domain name and level 3 domain name can read this Cookie without any setting.
Set-Cookie: key=value; domain=.example.com; path=/
Copy the code

AJAX

The same-origin policy states that AJAX requests can only be sent to same-origin urls, otherwise an error will be reported. Several ways to circumvent it

  • JSONP
  • WebSocket
  • CORS

JSONP

  • JSONP is a common way for servers and clients to communicate across sources. The biggest feature is simple to apply, the old browser all support, server transformation is very small.
  • The basic idea is that a web page requests JSON data from the server by adding a script element, which is not restricted by the same origin policy. The server receives the request and returns the data in a named callback function.

Front-end implementation:

function jsonP (url, callbackName = 'callback') {
    return new Promise((resolve, reject) = > {
        const scriptTag = document.createElement('script')
        scriptTag.src = url + `? cb=${callbackName}`
        scriptTag.setAttribute('type'.'text/javascript')
        document.body.appendChild(scriptTag)

        window[callbackName] = function jsonPCallback (data) {
            if (data) resolve(data)
            else reject(new Error('no data'))

            document.body.removeChild(scriptTag)
        }
    })
}

jsonP('http://localhost:3000/jsonp').then(res= > {
    this.res = JSON.stringify(res)
})

// Return sample data
/ * * / typeof callback === 'function' && callback({"data": {"name":"Tom"}});
Copy the code

Server implementation (Express as an example) :

// app.js adds the cb function name field, which is the front-end query parameter
app.set('jsonp callback name'.'cb')

// Just use jsonp to return
router.get('/jsonp'.function(req, res) {
  res.jsonp({data: {name: 'Tom'}})});/ / front end request instance: http://localhost:3000/jsonp? cb=callback
Copy the code

websocket

WebSocket is a communication protocol that prefixes ws:// (unencrypted) and WSS :// (encrypted). This protocol does not enforce the same origin policy and can be used for cross-source communication as long as the server supports it.

Basic implementation (socket.io)

Front end:

const socket = socketIo('http://localhost:3000/', {
    query: {
        auth: '123'
    }
})

ocket.on('connect'.() = > {
    this.connectStatus = 'Link successful -${socket.id}`
})

socket.on('disconnect'.() = > {
    this.connectStatus = 'Link broken'
})

socket.on('connect_error'.(err: Error) = > {
    this.connectStatus = 'Link failed -${err.message}`
})

socket.on('Hi'.(message: string) = > {
    this.message = message
})
Copy the code

Server-side implementation:

const io = require('socket.io') ({path: '/socket.io'.serveClient: false
});

io.on('connect'.(socket) = > {
    // Verify cross-domain source information
    if(! ['http://localhost:8080'].includes(socket.handshake.headers.origin)) {
        return socket.disconnect()
    }

    socket.emit('Hi'.'Hello');
})

io.attach(server, {
    pingInterval: 10000.pingTimeout: 5000.cookie: false
});

Copy the code

Browser Cross-domain resource sharing -CORS

1. An overview of the

  • It allows browsers to issue XMLHttpRequest requests across source servers, overcoming the limitation that AJAX can only be used in the same source.
  • Cross-source resource sharing standards have added a new set of HTTP header fields that allow servers to declare which source sites have access to which resources through the browser.
  • The specification requires that for HTTP request methods that may have adverse effects on server data, the browser must first issue a precheck request using the OPTIONS method to know whether the server will allow the cross-source request. The actual HTTP request is made only after the server confirms that it is allowed. In the return of the precheck request, the server side can also inform the client whether it needs to carry identity credentials (including Cookies and HTTP authentication related data).

2. Add header information

Request header information
  1. Origin Indicates the current source information. The part field indicates the source of the precheck request or the actual request.
  2. Access-control-request-headers is used to pre-check the Request and tell the server about the additional header field. The comma split
  3. Access-control-request-method is used to precheck requests and tell the server which Request Method to use.
Response header information
  1. Access-control-allow-origin the access-Control-allow-origin server allows cross-domain source information.
  2. Access-control-allow-methods Methods by which the server prechecks request responses to Allow cross-domain requests.
  3. Access-control-expose-headers Preexamines the Headers that the server is allowed to carry in response to a request. This allows the front-end to read the Headers.
  4. Access-control-max-age Pre-check request response, which indicates how long the result of the pre-check request can be cached, in seconds.
  5. Access-control-allow-credentials Specifies whether the browser is allowed to read the response when the browser’s Credentials are set to true. When used in response to pre-detected requests, it specifies whether the actual request can use the credentials.

2. Access control scenario

A simple request

Such requests do not trigger precheck requests

  • Simple request methods: GET, HEAD, POST.
  • Header fields allowed: Accept, accept-language, content-language, content-Type (note additional restrictions), DPR, Downlink, save-data, viewport-width, Width
  • Content-type Allowed values: text/plain, multipart/form-data, application/ X-www-form-urlencoded

The header information carried by the request:

Origin: http://foo.example
Copy the code

Request response header information:

Access-Control-Allow-Origin: http://foo.example
Copy the code
Non-simple request

Non-simple requests send a precheck request to the server before the formal request, asking the server whether cross-domain requests are allowed and what request methods are allowed, header fields, and so on.

The header information carried by the precheck request:

Origin: http://foo.example
Access-Control-Request-Method: POST
Access-Control-Request-Headers: Content-Type
Copy the code

Precheck request response header information:

Access-Control-Allow-Origin: http://foo.example
Access-Control-Allow-Methods: POST, GET, OPTIONS
Access-Control-Expose-Headers: X-PINGOTHER, Content-Type
Access-Control-Max-Age: 86400
Copy the code

Request with identity credentials

  • The withCredentials flag of XMLHttpRequest is set to true to send Cookies to the server.
  • For requests with credentials, the server must not set access-Control-allow-origin to *. You must specify an explicit domain name that is consistent with the requested page.
  • Cookies still follow the same origin policy, only the Cookie set with the server domain name will be uploaded, cookies of other domain names will not be uploaded, and (cross-source) document. Cookie in the original web page code can not read cookies under the server domain name.
  • Access-control-allow-credentials need to be carried in response requests; if they are not carried or false, the simple request browser will not return the response content to the sender of the request. The precheck request will report an error.

Reference documentation

  1. Cross-source Resource Sharing (CORS) – MDN
  2. Cross-domain resource Sharing CORS – Ruan Yifeng