Computer programming miscellaneous knowledge -- 5 -- homology strategy

1 definition of homology strategy

Homology policy: a security policy provided by the browser. It means that the protocol, domain name and port are the same before they can access each other. That is, if the protocol, domain name and port are different, the browser prohibits the page from loading or executing scripts in different domains.

Since there is the concept of homology, there must be the concept of different homology. Next, let's take a group of examples to understand what is homology and what are different sources.

urlIs it homologous (and why)
http://www.example.com:80This url is compared with the following url
http://www.example.com:80/index.htmlSame origin (protocol, domain name and port are the same)
http://www.example.com:5000Different sources (different ports)
https://www.example.com:80Different sources (different protocols)
http://www.each.com:80Different sources (different domain names)

Why do browsers have homology policies? Because if there is no homology strategy, others can easily obtain the cookie information of our website or DOM operation on the web page. You know, this is very terrible, especially the cookie information. There is a sessionID in it, which is an important credential for the session session with the server. If someone gets the cookie, It may cause data theft and other consequences.

2 Application of homology strategy

We have understood the definition of homology strategy above, but it is still quite abstract. Let's take a look at what homology strategy is in practice, so as to have a deeper understanding of the definition of homology strategy.

2.1 project directory structure

Our main website is: http://127.0.0.1:5000

# app.py
import json
from flask import Flask, request, render_template


app = Flask(__name__)


@app.route('/')
def hello_world():
    return 'Hello World!'


@app.route('/index')
def index():
    return render_template('index.html')


@app.route('/test')
def helloworld():
    callback = request.args.get("callback")
    if not callback:
        return render_template('test.html')
    return_data = {"status": 200, "test": "test"}
    return callback + "(" + json.dumps(return_data) + ")"


if __name__ == '__main__':
    app.run(debug=True)
<!--test.html-->
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>test</title>
</head>
<body>
<strong>test</strong>
</body>
</html>

2. 2 request a script file in the same domain as itself

We request it through jquery's ajax http://127.0.0.1:5000/test

<!--index.html-->
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>index</title>
</head>
<body>
<strong>index</strong>

<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script>
    
	$.ajax({
	    url: 'http://127.0.0.1:5000/test',
	    type: 'get'
	})
	.done(data => {
	    console.log(data)
	})
</script>

</body>
</html>

Browser access results:

Because http://127.0.0.1:5000/test And http://127.0.0.1:5000/ It is homologous, so the successful request is successful, and the browser does not report an error.

2.3 request script files in different domains

We request it through jquery's ajax http://localhost:5000/test

<!--index.html-->
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>index</title>
</head>
<body>
<strong>index</strong>

<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script>
    
	$.ajax({
	    url: 'http://localhost:5000/test',
	    type: 'get'
	})
	.done(data => {
	    console.log(data)
	})
</script>

</body>
</html>

Browser access results:


Because http://locahost:5000/test And http://127.0.0.1:5000/ It is from different sources, so the browser will report the above error.

3 realize script file access in different domains

There are many ways to access script files in different domains. Here are some examples:

  1. Access through html several special tags
  2. Cross domain requests are implemented through jsonp
  3. Cross domain request is realized through CORS (cross domain resource sharing)
  4. Implement cross domain requests through agents (e.g. nginx, node Middleware)

3.1 access through several special html tags

In fact, several tags in html have src attributes, such as < script >, < link >, < img >, < iframe >. The src attribute of these tags is not restricted by the browser's homology policy, and can access script files in different domains. for instance:

<!--index.html-->
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>index</title>
</head>
<body>

<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>

</body>
</html>

We should all know that jquery can be introduced with external links. This is a typical example of avoiding the restriction of homology policy through src attribute.

3.2 realize cross domain request through jsonp

When you see jsonp, you can guess that this method is used when you need to request data across domains. Next, let's directly look at how to use it.

3.2.1 native implementation of jsonp cross domain request
<!--index.html-->
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>index</title>
</head>
<body>
<strong>index</strong>

<script>
	//This function is called after cross domain request.
    function showDate(data) {
        console.log(data)
    }
</script>
<script src="http://localhost:5000/test?callback=showDate"></script>

</body>
</html>

Browser access results:

Note: it can only be filtered through ALL [instead of Fetch/XHR] http://localhost:5000/test Because Fetch/XHR can only capture the request of XMLHttpRequest object.

3.2.2 jquery implements jsonp cross domain requests

In fact, jquery encapsulates jsonp in ajax requests. The principle is to create a script tag, and then splice the url string as the value of src attribute. In this way, the effect of cross domain request through jsonp is the same as that of native.

<!--index.html-->
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>index</title>
</head>
<body>
<strong>index</strong>

<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>

<script>
    $(function () {
        function showDate(data) {
            console.log(data)
        }
        $.ajax({
            url: 'http://localhost:5000/test',
            type: 'get',          //The request method must be get
            dataType: 'jsonp',    //Change the data type to jsonp
            jsonpCallback: 'showDate'   //Callback function called after data returns
        })
        .done(data => {
            console.log(data)
        })
    })
</script>

</body>
</html>

Browser access results:

3.3 realize cross domain request through CORS (cross domain resource sharing)

Does CORS look familiar? Yes, we made an example of cross domain request error reporting above. The error reporting information in the figure includes this abbreviation, so cross domain requests can also be realized through CORS (cross domain resource sharing). Because I don't study this very deeply, I'll simply say how to use it.

We need to http://localhost:5000/ To request the test.html file below it, we just need the server to set the properties of the corresponding header to complete it. No matter who cross domain requests test.html under the domain, no error will be reported due to the same source policy. In fact, this is a little bad. Anyone can access it. Isn't it very dangerous.

Access-Control-Allow-Origin:*
Access-Control-Allow-Methods:POST,GET,OPTIONS
Access-Control-Allow-Headers:Origin,x-requested-with,content-type,Accept

My description of this method is vague, because I haven't studied it in depth, so it may be a little wrong, but it is indeed a cross domain request method. If you are interested, you can go to a log of Mr. Ruan Yifeng explaining CORS - detailed explanation of cross domain resource sharing CORS- Ruan Yifeng's Weblog

3.4 cross domain request through proxy

We all know that the same origin policy comes with the browser. If we want to avoid the same origin policy from making cross domain requests, we can make requests through the proxy server. For example, if we request a script file in a different domain, we can first request a url in the same domain and then jump through the proxy server, Finally, the script file requested by the proxy server is returned. This is more abstract. Let's take a node middleware as an example (in fact, nginx can also):

//Introducing express framework
const express = require('express');
//Introducing agent middleware
const { createProxyMiddleware } = require('http-proxy-middleware');
//Create service instance
const app = express();

// Using the proxy middleware, the first parameter is the url we need to proxy
//                   The second parameter is the url of the jump
app.use('/api', createProxyMiddleware({ target: 'http://localhost:5000', changeOrigin: true }));

//Monitor 5000 ports
app.listen(5000);

After the above configuration, we request http://localhost:5000/test The proxy server will automatically jump to http://localhost:5000/test In this way, we will complete the cross domain request and the browser will not report an error.

If you want to learn more about this middleware, you can go to github to see the detailed introduction of the middleware author. A jump link is attached below—— HTTP proxy middleware GitHub address

In fact, nginx can also complete the role of an agent. I won't explain more here. If you want to know, you can query the documents and learn by yourself.

Conclusion
Well, the introduction of homology strategy is almost the same. Some are detailed and some are brief. That is also the embodiment of the author's level. When my level is high, I will continue to improve the article. I hope this article can help you. If there is anything wrong, you are also welcome to comment and correct. Thank you~

Reference blog

3.3 future content has not been tested. Finally, see the reference blog

Posted by vidago on Sun, 10 Oct 2021 04:51:10 -0700