spring boot cross domain problem

Keywords: Java Google Javascript Spring

Cross domain refers to mutual access between different domain names. 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. That is to say, if we want to use Ajax to get specific content in site B in site A, if site A is not in the same domain as site B, then cross domain access problems will occur.

What is the same domain? The same protocol, the same ip, the same port, and one of the three sames result in cross domain. That is to say, there must be a cross domain problem for front-end and back-end separation, because it is not the same service, or different ip, or different ports.

To solve this problem in spring boot, simply add the following configuration:

 1 import org.springframework.context.annotation.Bean;
 2 import org.springframework.context.annotation.Configuration;
 3 import org.springframework.web.cors.CorsConfiguration;
 4 import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
 5 import org.springframework.web.filter.CorsFilter;
 6 
 7 /**
 8  * Cross domain configuration
 9  */
10 @Configuration
11 public class CorsConfig {
12   // Set allow cross domain sources
13   private static String[] originsVal = new String[]{
14       "127.0.0.1:8080",
15       "localhost:8080",
16       "google.com",
17       "mail.google.com"
18   };
19 
20   /**
21    * Cross domain filter
22    *
23    * @return
24    */
25   @Bean
26   public CorsFilter corsFilter() {
27     UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
28     CorsConfiguration corsConfiguration = new CorsConfiguration();
29     this.addAllowedOrigins(corsConfiguration);
30     corsConfiguration.addAllowedHeader("*");  //Add access allowed headers
31     corsConfiguration.addAllowedMethod("*");  //Add access allowed method
32     corsConfiguration.addAllowedOrigin("*");  //Add the allowed sources. The * here already contains the source information in the originsVal array
33     source.registerCorsConfiguration("/**", corsConfiguration);
34     return new CorsFilter(source);
35   }
36 
37   private void addAllowedOrigins(CorsConfiguration corsConfiguration) {
38     for (String origin : originsVal) {
39       corsConfiguration.addAllowedOrigin("http://" + origin);
40       corsConfiguration.addAllowedOrigin("https://" + origin);
41     }
42   }
43 }

Posted by andrewmay67 on Mon, 02 Dec 2019 01:27:24 -0800