Spring boot microservice configuration Cors to solve cross domain request problem

Catalog

1. Architecture design

1.1 brief description

2. Cross domain Cors principle and popular science

2.1 what is cross domain?

2.2 under what circumstances will cross domain occur?  

2.3 how to avoid cross domain?

3. Cross domain solution cases

3.1 introduce the actual situation and go straight to the guy

3.2 nginx is used as a reverse agent and configured directly

3.3 spring boot server global Cors configuration code

4. The solution of this problem was initiated by the following big men

1. Architecture design

1.1 brief description

  1. The front end initiates the post request;
  2. nginx receives the post request and processes it, and the agent jumps to the address of zuul.
  3. The environment of this architecture is described in detail as follows:
    1. The front end is tested on the local notebook, i.e. IP is localhost or 127.0.0.1;
    2. Nginx 1.16 and springboot 2.0 microservices are on purchased alicloud servers.
    3. Add the mapping relationship between ip address and domain name in the local c:\Windows\System32\Drivers\etc\hosts file;
    4. 127.0.0.1 www.xxx.com mapping is added to / etc/hosts of alicloud server.

2. Cross domain Cors principle and popular science

2.1 what is cross domain?

Cross domain means that the browser cannot execute scripts of other websites. It is caused by the browser's homology policy, and it is the browser's security restrictions on javascript. In the same interface case, some requests written by postman, java or python can get the returned data, but the browser can't. the browser's security restrictions must be solved before access. If they are not solved, an error will always be reported:

Browser side

nginx terminal

2.2 under what circumstances will cross domain occur?  

The so-called homology means that the domain name, protocol and port are all the same. It doesn't matter if you don't understand it. Take a chestnut 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 main domain name: 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 protocol: http/https, cross domain)

Note that both localhost and 127.0.0.1 point to the native, but they are also cross domain.

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

2.3 how to avoid cross domain?

I feel that if it is accessed from the front end, it cannot be spared. It can only be fundamentally solved by the following three settings.

At first, we planned to let the front-end solve the problem by itself, but it could never be solved. When I realized that the front-end could not solve the problem, I positioned the problem at nginx, and started the failure of Xiaobian. Because Xiaobian has been engaged in data work, and it's the first time to really contact the web, and it's the first time to meet cross domain, to search all kinds of data on the Internet, and finally The solution is always the same. When the server of nginx.conf of nginx is modified over and over again and fails to work, the editor finds that some places still don't understand why the origin is always null, and the prompt is as follows: the nginx prompt 40320 is (the server has received the request, but it is forbidden to process), which really catches me. Later, he thinks about the server. There's a problem in. It's found. A configuration item is missing.

addAllowedOrigin("null")

After the configuration is completed, the jar package is newly printed and the test is passed.

3. Cross domain solution cases

3.1 introduce the actual situation and go straight to the guy

//The small demo requested by the front-end post and the supporting. js file have not been uploaded. If you need any comrades, please contact me.


<html>
<head>
    <meta charset="utf-8"/>
    <title>testinter</title>
</head>
<body>
<div>
    <input type="text" value="xxxxxx@qq.com" class="emailInput"><button class="btnSend">Send email verification code</button>
</div>
<div><button class="btnCheck">Verify user data</button></div>
<script src="./js/jquery-3.4.1.min.js"></script>
<script>
 $(".btnSend").click(function(){
   let fd=new FormData();
   fd.append("mailbox",$(".emailInput").val());
   fd.append("unix_time",Math.floor(new Date().getTime() / 1000))
   $.ajax({
     url: 'http://www.xxx.com:9090/api/user/code',
     type: 'post',
     processData: false,//important
     contentType: false,//important
     data: fd,
     success: function (res) {
       alert(JSON.stringify(res));
     }
   });
 });
</script>
</body>
</html>

3.2 nginx is used as a reverse agent and configured directly

//server configuration of nginx
 server {
        listen       9090;
        server_name  www.xxx.com;

        proxy_set_header X-Forwarded-Host $host;
        proxy_set_header X-Forwarded-Server $host;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header Host $host;


        location /{
                proxy_pass http://127.0.0.1:9000; / / address and end slogan of reverse agent
                proxy_connect_timeout 600;
                proxy_read_timeout 600;
        }
    }

3.3 spring boot server global Cors configuration code

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

/**
 * Using CORS to solve the problem of ajax cross domain access
 */
@Configuration
public class CorsGlobalConfig {
    private static final Logger logger = LoggerFactory.getLogger(CorsGlobalConfig.class);
    @Bean
    public CorsFilter corsFilter() {
        //1. Add CORS configuration information
        CorsConfiguration config = new CorsConfiguration();
        //1) do not write * or null in the allowed domain, otherwise the cookie will not be used, but null can not be avoided during local test.
        config.addAllowedOrigin("http://www.xxx.com");
        config.addAllowedOrigin("null");
        //2) send Cookie information or not
        config.setAllowCredentials(true);
        //3) allowed request mode
        config.addAllowedMethod("OPTIONS");
        config.addAllowedMethod("HEAD");
        config.addAllowedMethod("GET");
        config.addAllowedMethod("PUT");
        config.addAllowedMethod("POST");
        config.addAllowedMethod("DELETE");
        config.addAllowedMethod("PATCH");
        // 4) allowed header information
        config.addAllowedHeader("*");
        config.setMaxAge(3600L);
        //2. Add mapping path, and we will intercept all requests.
        UrlBasedCorsConfigurationSource configSource = new UrlBasedCorsConfigurationSource();
        configSource.registerCorsConfiguration("/**", config);

        //3. Return to the new CorsFilter.
        return new CorsFilter(configSource);
    }
}

4. The solution of this problem was initiated by the following big men

https://www.cnblogs.com/yuansc/p/9076604.html

Keywords: Nginx PHP Spring Javascript

Added by russthebarber on Sun, 27 Oct 2019 12:03:53 +0200