Springboot before 2.4

public class CorsFilterConfig {
    private CorsConfiguration buildConfig(a) {
        CorsConfiguration config = new CorsConfiguration();
        // Allow cookies to cross domains
        config.setAllowCredentials(true);
        // Allow the request to be submitted to the server URI, * indicates all allowed. Try to limit the source domains here, such as http://xxxx:8080, to reduce security risks.
        config.addAllowedOrigin("*");
        // Allow access to the header,* represents all
        config.addAllowedHeader("*");
        // Precheck request cache time (seconds), i.e., the same cross-domain request will not be prechecked again during this time
        config.setMaxAge(18000L);
        * indicates that all requests are allowed. You can also set GET, PUT, and so on separately
        config.addAllowedMethod("*");

        return config;
    }

    @Bean
    public CorsFilter corsFilter(a) {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/ * *", buildConfig());
        return newCorsFilter(source); }}Copy the code

After springboot2.4

public class CorsFilterConfig {
    private CorsConfiguration buildConfig(a) {
        CorsConfiguration config = new CorsConfiguration();
        // Allow cookies to cross domains
        config.setAllowCredentials(true);
        // Allow the request to be submitted to the server URI, * indicates all allowed. Try to limit the source domains here, such as http://xxxx:8080, to reduce security risks.
        // Allow access to the header,* represents all
        List<String> allowed = new ArrayList<>();
        allowed.add(CorsConfiguration.ALL);
        config.setAllowedOriginPatterns(allowed);
        // Precheck request cache time (seconds), i.e., the same cross-domain request will not be prechecked again during this time
        config.setMaxAge(18000L);
        * indicates that all requests are allowed. You can also set GET, PUT, and so on separately
        config.addAllowedMethod(CorsConfiguration.ALL);
        config.addAllowedHeader(CorsConfiguration.ALL);

        return config;
    }

    @Bean
    public CorsFilter corsFilter(a) {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/ * *", buildConfig());
        return newCorsFilter(source); }}Copy the code