Detailed Spring Boot settings to support cross-domain request process

For security reasons, modern browsers must comply with the same-origin policy when making HTTP requests. Otherwise, they are cross-domain HTTP requests, which are prohibited by default. The IP (domain name) is different, or the port is different, and the protocol is different (such as HTTP, HTTPS) will cause cross-domain problems.

The general front-end solutions are:

① Use JSONP to support cross-domain requests. The principle of JSONP to achieve cross-domain requests is simply dynamic creation

② Use the reaction proxy mechanism to solve cross-domain problems. When the front-end requests, the request is first sent to the back-end of the same source address, and the back-end request is forwarded to avoid cross-domain access.

Later, HTML5 supported the CORS protocol. CORS is a W3C standard. The full name is "Cross-origin resource sharing". It allows browsers to send XMLHttpRequest requests to cross-origin servers, thus overcoming the restriction that AJAX can only be used from the same source. It adds a special Header [Access-Control-Allow-Origin] to the server to tell the client about cross-domain restrictions. If the browser supports CORS and determines that the Origin is passed, it will allow XMLHttpRequest to initiate cross-domain requests.

If the front-end uses the CORS protocol, the back-end needs to be configured to support non-same-origin requests. There are two ways in Spring Boot to support non-same-origin requests.

First, configure CorsFilter.

@Configuration
public class GlobalCorsConfig {
  @Bean
  public CorsFilter corsFilter() {
    CorsConfiguration config = new CorsConfiguration();
     config.addAllowedOrigin("*");
     config.setAllowCredentials(true);
     config.addAllowedMethod("*");
     config.addAllowedHeader("*");
     config.addExposedHeader("*");

    UrlBasedCorsConfigurationSource configSource = new UrlBasedCorsConfigurationSource();
    configSource.registerCorsConfiguration("/**", config);

    return new CorsFilter(configSource);
  }
}

Need to configure the above piece of code. The second way is slightly simpler.

Second, add to the startup class:

public class Application extends WebMvcConfigurerAdapter { 

  @Override 
  public void addCorsMappings(CorsRegistry registry) { 

    registry.addMapping("/**") 
        .allowCredentials(true) 
        .allowedHeaders("*") 
        .allowedOrigins("*") 
        .allowedMethods("*"); 

  } 
} 

Some high-frequency interview questions collected in the latest 2020 (all organized into documents), there are many dry goods, including mysql, netty, spring, thread, spring cloud, jvm, source code, algorithm and other detailed explanations, as well as detailed learning plans, interviews Question sorting, etc. For those who need to obtain these contents, please add Q like: 11604713672

Guess you like

Origin blog.csdn.net/weixin_51495453/article/details/113616269