This article has participated in the “Digitalstar Project” and won a creative gift package to challenge the creative incentive money

1. What is cross-domain

When the protocol, domain name, or port of a URL request is different from the current page URL, it is called cross-domain

Current page URL Url of the requested page Whether the cross-domain why
www.test.com/ www.test.com/index.html no Same-origin (same protocol, domain name, and port number)
www.test.com/ www.test.com/index.html Cross domain Different protocols (HTTP/HTTPS)
www.test.com/ www.baidu.com/ Cross domain Different master domain name (test/baidu)
www.test.com/ blog.test.com/ Cross domain Different subdomains (WWW /blog)
www.test.com:8080/ www.test.com:7001/ Cross domain Different port numbers (8080/7001)

Requests are restricted by the same origin policy because of domain inconsistencies and because of security issues

Typically, browsers place restrictions on cross-domain requests. Browsers restrict cross-domain requests for security reasons because cross-domain requests can be used by criminals to launch CSRF attacks.

2. CSRF attacks

2.1 CSRF instructions

One Click Attack/Session Riding CSRF (Cross-site Request Forgery)

CSRF attacker induces the user to visit an attack page after the user has logged in to the target website, takes advantage of the target website’s trust to the user, launches forged user operation request to the target website on the attack page as the user, and achieves the attack purpose.

2.1 the principle

The principle of CSRF attack is described as follows:

  1. There are two websites, of which website A is A truly trusted website and website B is A dangerous website.
  2. When A user logs in to the trusted website OF A, cookies related to the website of A will be stored locally, and the browser will also maintain this Session Session.
  3. At this time, if the user visits dangerous website B without logging out of website A, then dangerous website B can simulate sending A request to website A (cross-domain request) to operate on website A
  4. From the perspective of website A, it does not know that the request is issued by website B (both Session and Cookie are from website A), so it successfully launches A CSRF attack.

Thus, a CSRF attack can be simply understood as: an attacker steals your identity and sends requests on your behalf.

CSRF can do things like: send emails in your name, send messages, steal your account, even buy goods, virtual currency transfer…… The problems include personal privacy leakage and property security.

3. CORS

3.1 introduction

Cross-origin Resource Sharing(CORS) is a new W3C standard that adds a set of HTTP header fields that allow servers to declare which source sites have access to which resources.

In other words, it allows the browser to make XMLHttpReuest requests to cross-domain servers that have declared CORS, overcoming the limitation that Ajax can only be used in the same source

A brief introduction to the new HTTP header field in CORS

  • Access-Control-Allow-Origin

This header can be carried in the response header to indicate which domains the server allows access to the resource

c.Header("Access-Control-Allow-Origin"."*")        
Copy the code
  • Access-Control-Allow-Methods

Precheck the response to the request, indicating which HTTP methods are allowed for the actual request

c.Header("Access-Control-Allow-Methods"."POST, GET, OPTIONS, PUT, DELETE,UPDATE")    
Copy the code
  • Access-Control-Allow-Headers

The header field is used to precheck the response to the request and indicates which header fields are allowed in the actual request

c.Header("Access-Control-Allow-Headers"."Authorization, Content-Length, X-CSRF-Token, Token,session,X_Requested_With,Accept, Origin, Host, Connection, Accept-Encoding, Accept-Language,DNT, X-CustomHeader, Keep-Alive, User-Agent, X-Requested-With, If-Modified-Since, Cache-Control, Content-Type, Pragma")
Copy the code
  • Access-Control-Max-Age

The header field is used for the response to the precheck request and specifies how long the precheck request can be cached.

c.Header("Access-Control-Max-Age"."172800")  
Copy the code
  • Access-Control-Allow-Credentials

The header field is used to precheck the response to the request, indicating which HTTP methods are allowed for the actual request.

c.Header("Access-Control-Allow-Credentials"."false")       
Copy the code

3.2 reference

Set up in the middleware to write!

func Cors(a) gin.HandlerFunc {
	return func(c *gin.Context) {
		method := c.Request.Method      	      // Request method
		origin := c.Request.Header.Get("Origin")  // Request headers
		var headerKeys []string                   // declare the request header keys
		for k := range c.Request.Header {
			headerKeys = append(headerKeys, k)
		}
		headerStr := strings.Join(headerKeys, ",")
		ifheaderStr ! ="" {
			headerStr = fmt.Sprintf("access-control-allow-origin, access-control-allow-headers, %s", headerStr)
		} else {
			headerStr = "access-control-allow-origin, access-control-allow-headers"
		}
		iforigin ! ="" {
			c.Writer.Header().Set("Access-Control-Allow-Origin"."*")
			c.Header("Access-Control-Allow-Origin"."*")        
			// This allows access to all domains
			c.Header("Access-Control-Allow-Methods"."POST, GET, OPTIONS, PUT, DELETE,UPDATE")      
			// All cross-domain request methods supported by the server, in order to avoid multiple 'pre-check' requests per browse request
			// The type of header
			c.Header("Access-Control-Allow-Headers"."Authorization, Content-Length, X-CSRF-Token, Token,session,X_Requested_With,Accept, Origin, Host, Connection, Accept-Encoding, Accept-Language,DNT, X-CustomHeader, Keep-Alive, User-Agent, X-Requested-With, If-Modified-Since, Cache-Control, Content-Type, Pragma")
			// Allow cross-domain Settings and return other subsegments
			c.Header("Access-Control-Expose-Headers"."Content-Length, Access-Control-Allow-Origin, Access-Control-Allow-Headers,Cache-Control,Content-Language,Content-Type,Expires,Last-Modified,Pragma,FooBar")      
			// Cross-domain key Settings are parsed by browsers
			c.Header("Access-Control-Max-Age"."172800")        
			// Cache request information in seconds
			c.Header("Access-Control-Allow-Credentials"."false")       
			// Whether cross-domain requests require cookie information The default value is true
			c.Set("content-type"."application/json")      
			// Set the return format to JSON
		}
		// Allow all OPTIONS methods
		if method == "OPTIONS" {
			c.JSON(http.StatusOK, "Options Request!")
		}
		c.Next()        // Process the request}}Copy the code

Use with GIN framework

	r:=gin.Default()
	r.Use(middleware.Cors())
Copy the code

References 1, www.jianshu.com/p/f880878c1… 2, blog.csdn.net/qq_38128179…