1. What is cross-domain

Cross-domain interception is caused by the same origin policy of the browser. The same origin policy is the core and basic security function of the browser. Same-origin (that is, in the same domain) means that two pages have the same protocol, host, and port number.

The Same Origin policy is a convention. It is the core and most basic security function of a browser. If the Same Origin policy is absent, the normal functions of the browser may be affected. The Web is built on the same origin policy, and browsers are just an implementation of the same origin policy.

There are two types of same-origin policies:

  • DOM same-origin policy: Operations on DOM of different source pages are prohibited. In this case, iframes of different domain names are restricted from accessing each other.
  • XMLHttpRequest Same-origin policy: Disables the use of XHR objects to make HTTP requests to server addresses of different sources.

The same origin policy not only solves the security of browser access, but also brings cross-domain problems. When the protocol, domain name, or port of a URL request is different from the current PAGE URL, it is called cross-domain.

2. Use CORS to solve cross-domain problems

Cross-origin Resource Sharing (CORS) is a W3C standard that defines how browsers and servers should communicate when they must access cross-domain resources. The basic idea behind 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. 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.

Browsers classify CORS requests into two categories: Simple request and not-so-simple Request.

2.1 Simple Request

A simple request is one that meets the following two criteria:

  • The request method can be HEAD, GET, or POST.
  • HTTP headers do not exceed the following types:
    • Accept
    • Accept-Language
    • Content-Language
    • Last-Event-ID
    • Application/X-www-form-urlencoded, multipart/form-data, text/plain

For simple requests, the browser automatically adds an Origin field to the header of the request to indicate the source (protocol, domain name, and port number) from which the request is sent. The server determines whether to accept the request based on this value. If Origin is within the license, the server returns a response with several more headers:

Access-Control-Allow-Credentials: true
Access-Control-Allow-Headers: Content-Type, Content-Length
Access-Control-Allow-Origin: *
Content-Type: text/html; charset=utf-8
Copy the code

In fact, these parameters are then configured to handle cross-domain requests.

2.2 Non-simple Requests

Non-simple requests are requests that have special requirements on the server, such as the request method being PUT or DELETE, or the content-Type field being of Type Application/JSON.

CORS requests that are not simple requests will add an HTTP preflight request before the official communication. The preflight request is called OPTIONS request. In the header, the key field Origin indicates the source from which the request is coming. In addition to the Origin field, the precheck header contains two special fields:

// This field is required to list the HTTP methods used by the browser for CORS requests
Access-Control-Request-Method
// This field is a comma-separated string that specifies the additional header fields that the browser will send in CORS requests.
Access-Control-Request-Headers
Copy the code

The browser asks the server if the domain name of the current web page is on the server’s license list, and what HTTP verb and header fields can be used. The browser will only issue a formal one if it receives a positive responseXMLHttpRequestRequest, otherwise an error is reported.

2.3 Configuring CORS to Resolve cross-domain problems

The two types of cross-domain requests described above include several special Header fields that ARE configured by CORS to solve cross-domain problems:

Access-Control-Allow-Origin
Copy the code

This field is required. Its value is either the value of the Origin field at the time of the request, or an *, indicating acceptance of requests for any domain name

Access-Control-Allow-Methods
Copy the code

This field is required, and its value is a comma-separated string indicating all methods supported by the server for cross-domain requests. Notice that all supported methods are returned, not just the one requested by the browser. This is to avoid multiple “pre-check” requests.

Access-Control-Allow-Headers
Copy the code

The access-Control-allow-HEADERS field is required if the browser Request includes the access-Control-request-HEADERS field. It is also a comma-separated string indicating all header information fields supported by the server, not limited to those requested by the browser in precheck.

Access-Control-Expose-Headers
Copy the code

This field is optional. In CORS requests, the response of the XMLHttpRequest object only gets six basic fields: Cache-Control, Content-Language, Content-Type, Expires, Last-Modified, and Pragma. If you want to get other fields, you must specify access-Control-expose-headers.

Access-Control-Allow-Credentials
Copy the code

This field is optional. Its value is a Boolean value indicating whether cookies are allowed to be sent. By default, cookies are not included in CORS requests. If set to true, the server explicitly approves that cookies can be included in the request and sent to the server. This value can only be set to true if the server does not want the browser to send cookies.

Access-Control-Max-Age
Copy the code

This field is optional and specifies the validity period of the precheck request, in seconds. During this period, no other precheck request is sent.

3.Golang solves cross-domain interception

Using the Gin framework as an example, configure middleware to handle cross-domain:

func Cors(context *gin.Context) {
	method := context.Request.Method
	// Must accept the request of the specified domain. * can be used without restriction, but it is not safe
	//context.Header("Access-Control-Allow-Origin", "*")
	context.Header("Access-Control-Allow-Origin", context.GetHeader("Origin"))
	fmt.Println(context.GetHeader("Origin"))
	// You must set the methods for all cross-domain requests supported by the server
	context.Header("Access-Control-Allow-Methods"."POST, GET, PUT, DELETE, OPTIONS")
	// All header fields supported by the server, not limited to those requested by the browser in "precheck"
	context.Header("Access-Control-Allow-Headers"."Content-Type, Content-Length, Token")
	// Optionally, set the extra fields available to the XMLHttpRequest response object
	context.Header("Access-Control-Expose-Headers"."Access-Control-Allow-Headers, Token")
	// Optional whether to allow subsequent requests to carry authentication information Cookir. The value can only be true
	context.Header("Access-Control-Allow-Credentials"."true")
	// Allow all OPTIONS methods
	if method == "OPTIONS" {
		context.AbortWithStatus(http.StatusNoContent)
		return
	}
	context.Next()
}
Copy the code

Note: Context.Header(” access-Control-allow-origin “, “*”) if setting access-Control-allow-origin to * does not Allow XMLHttpRequest to carry cookies, So to implement wildcard, you can dynamically get Origin, namely context.getheader (“Origin”).

The native HTTP package is similar to the operation response header.