Solutions to cross domain and cross domain problems

Keywords: Front-end Ajax http

Cross domain

What is cross domain?

Cross domain, that is, non homologous policy requests. This means that the browser cannot execute scripts from other websites. It is caused by the browser's homology policy and is a security restriction imposed by the browser.

The so-called homology means that the domain name, protocol and port are the same. It doesn't matter if you don't understand. For example:

  • http://www.123.com/index.html Call http://www.123.com/server.php (non cross domain)
  • http://www.123.com/index.html Call http://www.456.com/server.php (different primary domain names: 123 / 456, cross domain)
  • http://abc.123.com/index.html Call http://def.123.com/server.php (different subdomains: abc/def, cross domain)
  • http://www.123.com:8080/index.html Call http://www.123.com:8081/server.php (different ports: 8080 / 8081, cross domain)
  • http://www.123.com/index.html Call https://www.123.com/server.php (different protocols: http/https, cross domain)

Note: Although both localhost and 127.0.0.1 point to the local machine, they also belong to cross domain.

When the browser executes a javascript script, it will check which page the script belongs to. If it is not a homologous page, it will not be executed.

  1. Cross domain only exists on the browser side, not in other environments such as Android / IOS / node.js/python/java
  2. The cross domain request can be sent out, and the server can receive the request and return the result normally, but the result is intercepted by the browser.
  3. For security reasons, the browser must follow the same origin policy when using the XMLHttpRequest object to initiate HTTP requests. Otherwise, it is a cross domain HTTP request, which is prohibited by default. In other words, the cornerstone of browser security is the homology policy.
What is CORS?

CORS is a W3C standard. Its full name is "cross Origin resource sharing". It allows browsers to send XMLHttpRequest requests to cross source servers, thus overcoming the limitation that AJAX can only be used in the same source. It adds a special header [access control allow Origin] to the server to tell the client about the cross domain restrictions. If the browser supports CORS and determines that Origin passes, it will allow XMLHttpRequest to initiate cross domain requests.

CORS Header

Access-Control-Allow-Origin: http://www.xxx.com
Access-Control-Max-Age: 86400
Access-Control-Allow-Methods: GET, POST, OPTIONS, PUT, DELETE
Access-Control-Allow-Headers: content-type
Access-Control-Allow-Credentials: true
Interpretation of meaning:
1. Access control allow origin http://www.xxx.com Domain (self setting, here is only an example) initiates cross domain requests
2. Access control Max age is set to 86400 seconds, and no pre verification request needs to be sent
3. Access control allow methods sets the methods that allow cross domain requests
4. Access control allow headers allows cross domain requests to contain content type
5. Access control allow credentials settings allow cookies

What actions are blocked across domains?

The browser implements this homology strategy from two aspects: one is the request for the interface, and the other is the query for Dom

  1. Blocking interface requests is easier to understand, for example, using ajax from http://192.168.100.150:8020/ Experiment / jsonp.html page http://192.168.100.150:8081/zhxZone/webmana/dict/jsonp The two url ports are different, so they belong to cross domain. No 'access control allow origin' header is present on the requested resource will be reported on the console printing desk

    • It is worth saying that although the browser prohibits the user from displaying and operating the requested returned data, the browser does request it. If the server does not make restrictions, it will return data. In the network in debugging mode, you can see that the return status is 200 and the returned data can be seen
  2. Block dom fetches and operations

    For example, if iframe is embedded in a page and src is a b page with different sources, the dom in b cannot be operated in a, and there is no way to change the css style in the dom in b.

Although this restriction of the browser can not guarantee complete security, it will increase the difficulty of attack

Although the security mechanism is very good and can resist the intrusion of bad people, sometimes we need to cross domain request interface data or operate our own dom, which is also blocked by the browser, so we need to cross domain

The premise of cross domain is that you are with the server. You can control the data returned by the server, otherwise cross domain cannot be completed

How to solve cross domain problems?

1. The front-end method uses jsonp

JSONP requires the server side to support JSONP requests

The principle is that the link, href and src attributes in html are not affected by cross domain. Link can call remote css files, href can be linked to any url, the src of pictures can reference pictures at will, and the src attribute of script can introduce js files of different origin at will

  • script
  • img
  • link
  • iframe
  • ...

These tags do not have cross domain request restrictions

eg:

$.ajax({
  url: 'http://1.119.169.72:10001/lidarData/lidarData/selectViewData?time=2020-07-05&lidarType=dep&wavelength=355',
  method: 'get',
  dataType: 'jsonp', //=>A JSONP request is executed
  success: res => {
    console.log(res);
  }
});

serverJsonp.js

let express = require('express'),
  app = express();
app.listen(10001, _ => {
  console.log('ok');
});

app.get('/selectViewData', (req, res) => {
  let {
    callback = Function.prototype
  } = req.query();
  let data = {
    code: 0,
    message: 'ddd'
  };
  res.send('${callback}(${JSON.stringify(data)})');
});

Problem: JSONP can only handle get requests

2. Background configuration solution cross domain

The background solves cross domain problems through configuration

First, introduce dependencies in pom.xml

<!--Cross domain dependency-->
<dependency>
    <groupId>com.thetransactioncompany</groupId>
    <artifactId>cors-filter</artifactId>
    <version>1.7.1</version>
</dependency>
<dependency>
    <groupId>com.thetransactioncompany</groupId>
    <artifactId>java-property-utils</artifactId>
    <version>1.9</version>
</dependency>
<dependency>

Then configure the filter in web.xml

<!--To allow cross domain access-->
<filter>
    <filter-name>CorsFilter</filter-name>
    <filter-class>com.thetransactioncompany.cors.CORSFilter</filter-class>
</filter>
<filter-mapping>
    <filter-name>CorsFilter</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

Is it convenient for the front end to request data across domains?

Note that if the login detection filter is configured in the project, there may be a conflict, because if there is no login, it will jump to the login interface every time...

WebMvcConfigurer of spring boot injection rewriting method solves cross domain problems

CORSConfig.java

/**
 * @Description Cross domain configuration
 * @Author chenlinghong
 * @Date 2019/1/27 13:31
 **/
@Configuration
public class CORSConfig {

    @Bean
    public WebMvcConfigurer corsConfigurer(){
        return new WebMvcConfigurer() {
            @Override
            public void addCorsMappings(CorsRegistry registry) {
                registry.addMapping("/**")
                        .allowedHeaders("*")
                        .allowedMethods("*")
                        .allowedOrigins("*");
            }
        };
    }
}

3. iframe based cross domain solution (window.name/document.domain/location.hash)

4. The new window.postMessage method introduced in HTML5 is used to transfer data across domains

5. Cross domain resolution through CORS

CORS also needs server-side support

The basic idea behind CORS is to use custom HTTP headers to allow browsers and servers to understand each other, so as to determine whether the request or response is successful or not

First write your own filter CORSFilter

/**
 * Created by 12143 on 2018/12/7.
 */
@Component
public class CORSFilter extends OncePerRequestFilter {
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        response.addHeader("Access-Control-Allow-Origin", "http://192.168.100.150:8020");
        //response.addHeader("Access-Control-Allow-Origin", "*");
        response.addHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE");
        response.addHeader("Access-Control-Allow-Headers", "Content-Type");
        response.addHeader("Access-Control-Max-Age", "1800");//30 min
        filterChain.doFilter(request, response);
    }
}

Note: if access control allow origin is *, all URLs are allowed to access. If it is *“ http://192.168.100.150:8020 ”Only this url can be accessed. Note that if there is a port, the port should also be written
For example, it is configured http://192.168.56.130:8081 , then only http://192.168.56.130:8081 Data can be obtained, otherwise all 403 exceptions are reported
Then add this filter in web.xml

<filter>
    <filter-name>CorsFilter</filter-name>
    <filter-class>com.xxx.common.filter.CORSFilter</filter-class>
</filter>
<filter-mapping>
    <filter-name>CorsFilter</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

6. Through Nginx reverse proxy

Posted by aragon1337 on Mon, 20 Sep 2021 21:49:55 -0700