Cross domain cors processing in Spring boot summary

background

Now many projects are separated from the front and back, which leads to a very common problem. Our pages and interfaces are under different domain names. When we access the back-end interface through ajax, there will be cross domain problems. How can we solve this problem? Generally speaking, they are cors and jsonp. Spring simplifies the configuration of cors. Let's take a look at the cors it provides.

WebMvcConfigurer object

We can initialize a WebMvcConfigurer object to configure our cors mapping.

@Configuration
public class CorsCongiguration {
    @Bean
    public WebMvcConfigurer corsConfigurer() {
        return new WebMvcConfigurerAdapter() {
            @Override
            public void addCorsMappings(CorsRegistry registry) {
                registry.addMapping("/api/**"); // Allow all third-party domain names to access the interface
                // . allowedOrigins("http://domain2.com") / / specify the source domain name
                // .allowedMethods("PUT", "DELETE")
                // .allowedHeaders("header1", "header2", "header3")
                // .exposedHeaders("header1", "header2")
                // .allowCredentials(false).maxAge(3600);
            }
        };
    }
}

Inherit WebMvcConfigurerAdapter

This is similar to the way above

@Configuration
@EnableWebMvc
public class CorsConfiguration_2 extends WebMvcConfigurerAdapter {

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/api/**");
    }
}

corsFilter

This method is rarely used now

@Component
@EnableWebMvc
public class CorsFilterCongiguration extends CorsFilter {

    public CorsFilterCongiguration(CorsConfigurationSource configSource) {
        super(configSource);
    }

    @Bean
    public FilterRegistrationBean corsFilter() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        CorsConfiguration config = new CorsConfiguration();
        config.setAllowCredentials(true);
        config.addAllowedOrigin("*");
//        config.addAllowedOrigin("http://domain1.com");
        config.addAllowedHeader("*");
        config.addAllowedMethod("*");
        source.registerCorsConfiguration("/api/**", config);
        FilterRegistrationBean bean = new FilterRegistrationBean(new CorsFilter(source));
        bean.setOrder(0); // Must be before all filters
        return bean;
    }

}

Tags: Spring

Posted on Wed, 15 Apr 2020 10:24:51 -0700 by CBaZ