[Browser Security Mechanism] This article takes you to understand the same origin policy (Same origin policy) and cross-domain requests

What is the Same Origin Policy

Same-origin policy (Same-origin policy) is a browser security mechanism used to restrict cross-domain operations between different origins. It is a rule that controls how the browser handles resources from different sources such as documents, scripts, style sheets, and AJAX requests.

In the same-origin policy, if two URLs have the same protocol (protocol), host (host) and port number (port), they are considered to be of the same origin (origin).

for example:
When the pages from Baidu and Google are opened in the two tab pages of a browser , when the Baidu tab page of the browser executes a script, it will check which page the script belongs to, that is, check whether it has the same origin. source script will be executed. If the source is not the same, when requesting data, the browser will report an exception in the console, prompting that the access is denied.

insert image description here
Note: cross-domain does not mean that the request cannot be sent, but that the request can be sent and the server can receive the request and return the result normally, but the result is intercepted by the browser.

Suppose a standard URL ishttp://store.company.com

Cross-domain examples are as follows:

insert image description here

Suppose a standard URL ishttp://www.a.com

Cross-domain examples are as follows:

insert image description here


Proposed purpose and limitations

The purpose of the same-origin policy is to protect the security and privacy of users. It prevents malicious websites from accessing users' sensitive information through cross-origin requests, or exploiting vulnerabilities on other websites.

The same-origin policy imposes the following restrictions:

  • JavaScript can only access pages and code from the same source.
  • DOM (Document Object Model) restricts access to different source documents.
  • The XMLHttpRequest and Fetch APIs limit AJAX requests to different origins.

Understanding the same-origin policy is critical to writing secure web applications and understanding solutions to cross-origin issues.

However, the same-origin policy is not suitable for all scenarios. To allow cross-origin requests, mechanisms such as Cross-Origin Resource Sharing (CORS) and server-side proxies can be used. The details are described next.


JSONP cross-domain communication

JSONP (JSON with Padding) is a <script>cross-domain communication technology using tags, which uses dynamically created tags to load data in cross-domain requests <script>. Here are the steps of how JSONP works:

  1. The client creates a dynamic <script>tag, specifies the URL address to be requested, and defines a callback function, which is called after the data loading is completed.
  2. After the server receives the request, it returns the response with the data wrapped in the callback function to the client.
  3. The client's browser processes the response data by executing the callback function.

The key point of JSONP is that the data returned by the server needs to be wrapped in a predefined callback function. In this way, even if it is a cross-domain request, the client can still <script>load data by dynamically creating tags, and execute a predefined callback function after the response is returned.

for example:

Suppose we have two websites: https://www.example.comand https://api.example.com. According to the same-origin policy, the two websites are considered to be of different origin.

In https://www.example.comthe page of , we want to get https://api.example.com/datathe data from , and https://api.example.comCORS is not enabled in , so JSONP cross-domain communication can be performed at this time.

  1. On the client side, we need to define a callback function to process the obtained data:

    function processData(data) {
          
          
        console.log(data);
    }
    
  2. Create a dynamic <script>tag, use it https://api.example.com/dataas its srcattribute value, and specify the callback function name as a query parameter, for example:

    var script = document.createElement('script');
    script.src = 'https://api.example.com/data?callback=processData';
    document.head.appendChild(script);
    
  3. When the browser loads the <script>tag, it will send a request to https://api.example.com/data?callback=processData, and the data that the server should return is wrapped in processData()a function, and the response content is as follows:

    processData({
          
           "message": "This is cross-origin data" });
    
  4. The browser parses the response and executes processData()the function, and the client can access the cross-domain requested data.

Through JSONP, we can implement cross-origin requests without enabling CORS.

have to be aware of is:JSONP has certain limitations (such as only supporting GET requests, security issues, etc.), and it relies on public callback functions, which may be at risk of malicious code injection. But it is a simple and effective solution when complex cross-origin requests are not required.


Cross-Origin Resource Sharing (CORS)

CORS is a mechanism that allows cross-origin requests to be controlled in browsers through specific HTTP headers. It is based on the server's trust model, and the server can send additional response headers to indicate whether the browser allows cross-origin requests. When a browser initiates a cross-domain request, it will perform a preflight request (OPTIONS request) to check the cross-domain operations allowed by the server. If the server returns the appropriate CORS response headers, the browser will perform the actual cross-origin request.

insert image description here
Browsers divide CORS requests into two categories: simple requests and non-simple requests.

Simple requests need to meet the following two conditions:

  1. The request method is one of three methods: HEAD, GET, POST.

  2. HTTP header information does not exceed the following fields: Accept, Accept-Language, Content-Language, Last-Event-ID, and Content-Type are limited to three valuesapplication/x-www-form-urlencoded、multipart/form-data、text/plain

CORS simple request cross-domain implementation process:

insert image description here

At the same time, it is also possible to allow cross-origin requests from specific sources on the server side:

# Python Flask 示例代码
from flask import Flask, jsonify

app = Flask(__name__)

@app.route('/data', methods=['GET'])
def get_data():
    response = jsonify({
    
    'message': 'This is a cross-origin response'})
    response.headers.add('Access-Control-Allow-Origin', 'https://www.example.com')
    response.headers.add('Access-Control-Allow-Methods', 'GET')
    return response

if __name__ == '__main__':
    app.run()

In the above code, Access-Control-Allow-Originand Access-Control-Allow-Methodsare CORS-related response headers, which instruct the browser to allow GET requests from specific sources.

Official documentation: https://developer.mozilla.org/zh-CN/docs/Web/HTTP/CORS


server-side proxy

A server-side proxy is a method of handling cross-origin requests by forwarding them on a server. It involves setting up a proxy server between the client and the target server, the client sends the request to the proxy server, the proxy server forwards the request to the target server, and returns the response to the client. Since the proxy server is in the same origin as the target server, there is no cross-domain problem.

Server proxy implementation process:

insert image description here

For example, when the client needs to https://api.example.com/datacommunicate across domains with , you can set a proxy route through the server /proxy, and then the client sends the request to /proxy/data, and the proxy server forwards the request to https://api.example.com/data, and returns the response to the client.

In this way, for the client, the request it sends is made in the same source (relative to the proxy server), avoiding cross-domain problems.


reverse proxy

A reverse proxy is an arrangement of proxy servers that forwards client requests to internal resource servers and returns responses to clients. Unlike the forward proxy, the reverse proxy provides services transparently, and the client does not need to know the server that actually provides the service.

Here's how a reverse proxy works and some key concepts:

  1. Client sends request to reverse proxy server eg https://www.example.com.

  2. After receiving the client request, the reverse proxy server decides which internal resource server to forward the request to for processing according to the predefined rules and routing configuration.

  3. A reverse proxy server forwards requests to internal resource servers, eg https://appserver1.example.com.

  4. After receiving the request, the internal resource server generates a response based on the service or content it provides and sends it back to the reverse proxy server.

  5. After the reverse proxy server receives the response from the internal resource server, it returns the response to the client.

insert image description here

In practical applications, the reverse proxy can be configured and built using common web server software (such as Nginx, Apache). With proper configuration, a reverse proxy can provide high-performance, secure, and scalable services.

for example:

Suppose you have a website https://www.example.comand want to serve multiple services on the website, such as static files, API and application. To improve performance and security, you decide to use a reverse proxy to manage these services.

(1) Configure the reverse proxy server:
You use Nginx as the reverse proxy server and configure accordingly.

(2) Static file serving:
On your internal resource server, you have a directory for storing static files, eg /var/www/html. You specify in your Nginx configuration that /staticrequests starting with a path be forwarded to this directory. For example:

location /static {
    
    
    alias /var/www/html;
}

When a client accesses https://www.example.com/static/file.jpg, Nginx will forward the request to the internal resource server's /var/www/html/file.jpgfile and return the response to the client.

(3) API service:
Your internal resource server also provides a set of API interfaces, such as /api/getDataand /api/saveData. You specify in the Nginx configuration that /apirequests starting with a path are forwarded to this API server. For example:

location /api {
    
    
    proxy_pass http://api-server;
}

When a client initiates https://www.example.com/api/getDataa request to , Nginx will forward the request to the API server on the internal resource server and return the response to the client.

By configuring a reverse proxy server, you can forward requests from different paths to different internal services, realizing service splitting and management. The client only needs to communicate with the reverse proxy server without directly accessing the internal resource server.

Several advantages and additional features of a reverse proxy:

  • Load balancing: The reverse proxy can distribute requests to multiple internal resource servers according to a pre-defined algorithm to achieve load balancing and improve performance and reliability.

  • Caching and Acceleration: Reverse proxies can cache responses, offloading internal resource servers and speeding up response times by serving local copies of static content.

  • Security filtering: The reverse proxy can perform security filtering between the client and the internal resource server to protect the internal resource server from malicious attacks, such as DDoS (distributed denial of service) attacks, SQL injection, etc.

  • Hiding the internal structure: The reverse proxy acts as the only entrance for external access. It can hide the real IP address of the internal resource server and the internal network structure, enhancing security.


Summarize

The above are knowledge points related to the same origin policy (Same origin policy) and cross-domain requests. It specifically introduces related technologies such as JSONP cross-domain communication, CORS, server-side proxy, and reverse proxy. Readers can learn more about it.

I am Qiu said , see you next time.

Guess you like

Origin blog.csdn.net/2301_77485708/article/details/132482937