Spring Boot忽略了我的CORS配置。

huangapple go评论100阅读模式
英文:

Spring Boot is ignoring my CORS configuration

问题

我有一个启用了CORS的REST API,但似乎Spring Boot忽略了我的CORS配置。以下是配置类:

  1. @Configuration
  2. @EnableWebSecurity
  3. public class SecurityConfiguration {
  4. @Value(value = "${cors.allowed-origins}")
  5. private List<String> allowedOrigins;
  6. @Bean
  7. public SecurityFilterChain securityFilterChain(HttpSecurity httpSecurity) throws Exception {
  8. return httpSecurity
  9. .csrf().disable().cors().configurationSource(this.corsConfigurationSource()).and()
  10. .authorizeHttpRequests().anyRequest().permitAll().and().build();
  11. }
  12. @Bean
  13. public CorsConfigurationSource corsConfigurationSource() {
  14. CorsConfiguration configuration = new CorsConfiguration();
  15. configuration.setAllowedOrigins(this.allowedOrigins);
  16. configuration.setAllowedMethods(Arrays.asList(
  17. HttpMethod.GET.name(), HttpMethod.POST.name(), HttpMethod.PUT.name(),
  18. HttpMethod.DELETE.name(), HttpMethod.HEAD.name(), HttpMethod.OPTIONS.name()
  19. ));
  20. configuration.setAllowedHeaders(Arrays.asList(
  21. HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, HttpHeaders.CONTENT_TYPE, HttpHeaders.ACCEPT,
  22. HttpHeaders.ORIGIN, HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, HttpHeaders.ACCESS_CONTROL_ALLOW_HEADERS,
  23. HttpHeaders.ACCESS_CONTROL_EXPOSE_HEADERS, HttpHeaders.AUTHORIZATION
  24. ));
  25. configuration.setExposedHeaders(Arrays.asList(
  26. HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD,
  27. HttpHeaders.ACCESS_CONTROL_ALLOW_HEADERS, HttpHeaders.ORIGIN, HttpHeaders.AUTHORIZATION
  28. ));
  29. configuration.setAllowCredentials(true);
  30. UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
  31. source.registerCorsConfiguration("/**", configuration);
  32. return source;
  33. }
  34. }

这是Spring Boot应用程序类:

  1. @SpringBootApplication(exclude = {UserDetailsServiceAutoConfiguration.class})
  2. public class RaioXcapeBackend {
  3. public static void main(String[] args) {
  4. SpringApplication.run(RaioXcapeBackend.class, args);
  5. }
  6. }

我知道CORS配置没有生效,因为API允许来自任何来源的请求(例如:我从本地运行的前端发送了一个GET请求),但我的目标是只允许来自一个来源,即我部署的前端应用程序域。

可能发生了什么?我已经检查过${cors.allowed-origins},它是正确的。

更新1

以下是对API的GET请求的标头:

  1. 响应标头
  2. Cache-Controlno-cacheno-storemax-age=0must-revalidate
  3. Connectionkeep-alive
  4. Content-Typeapplication/json
  5. DateMon19 Jun 2023 22:58:41 GMT
  6. Expires0
  7. Keep-Alivetimeout=60
  8. Pragmano-cache
  9. Transfer-Encodingchunked
  10. VaryAccess-Control-Request-Headers
  11. VaryAccess-Control-Request-Method
  12. VaryOrigin
  13. X-Content-Type-Optionsnosniff
  14. X-Frame-OptionsDENY
  15. X-Xss-Protection0
  16. 请求标头
  17. Accepttext/htmlapplication/xhtml+xmlapplication/xml;q=0.9image/avifimage/webpimage/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7
  18. Accept-Encoding:gzip,deflate,br
  19. Accept-Language:en,pt;q=0.9
  20. Cache-Control:no-cache
  21. Connection:keep-alive
  22. Dnt:1
  23. Host:localhost:8080
  24. Pragma:no-cache
  25. Sec-Ch-Ua:Not.A/Brand;v=8,Chromium;v=114,Google Chrome;v=114
  26. Sec-Ch-Ua-Mobile:?0
  27. Sec-Ch-Ua-Platform:Windows
  28. Sec-Fetch-Dest:document
  29. Sec-Fetch-Mode:navigate
  30. Sec-Fetch-Site:none
  31. Sec-Fetch-User:?1
  32. Upgrade-Insecure-Requests:1
  33. User-Agent:Mozilla/5.0(Windows NT 10.0;Win64;x64)AppleWebKit/537.36(KHTML,like Gecko)Chrome/114.0.0.0 Safari/537.36
英文:

I have a REST API with CORS enabled, but it seems like Spring Boot is ignoring my CORS configuration. Here it is the configuration class:

  1. @Configuration
  2. @EnableWebSecurity
  3. public class SecurityConfiguration {
  4. @Value(value = &quot;${cors.allowed-origins}&quot;)
  5. private List&lt;String&gt; allowedOrigins;
  6. @Bean
  7. public SecurityFilterChain securityFilterChain(HttpSecurity httpSecurity) throws Exception {
  8. return httpSecurity
  9. .csrf().disable().cors().configurationSource(this.corsConfigurationSource()).and()
  10. .authorizeHttpRequests().anyRequest().permitAll().and().build();
  11. }
  12. @Bean
  13. public CorsConfigurationSource corsConfigurationSource() {
  14. CorsConfiguration configuration = new CorsConfiguration();
  15. configuration.setAllowedOrigins(this.allowedOrigins);
  16. configuration.setAllowedMethods(Arrays.asList(
  17. HttpMethod.GET.name(), HttpMethod.POST.name(), HttpMethod.PUT.name(),
  18. HttpMethod.DELETE.name(), HttpMethod.HEAD.name(), HttpMethod.OPTIONS.name()
  19. ));
  20. configuration.setAllowedHeaders(Arrays.asList(
  21. HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, HttpHeaders.CONTENT_TYPE, HttpHeaders.ACCEPT,
  22. HttpHeaders.ORIGIN, HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, HttpHeaders.ACCESS_CONTROL_ALLOW_HEADERS,
  23. HttpHeaders.ACCESS_CONTROL_EXPOSE_HEADERS, HttpHeaders.AUTHORIZATION
  24. ));
  25. configuration.setExposedHeaders(Arrays.asList(
  26. HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD,
  27. HttpHeaders.ACCESS_CONTROL_ALLOW_HEADERS, HttpHeaders.ORIGIN, HttpHeaders.AUTHORIZATION
  28. ));
  29. configuration.setAllowCredentials(true);
  30. UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
  31. source.registerCorsConfiguration(&quot;/**&quot;, configuration);
  32. return source;
  33. }
  34. }

And here it is the Spring Boot application class:

  1. @SpringBootApplication(exclude = {UserDetailsServiceAutoConfiguration.class})
  2. public class RaioXcapeBackend {
  3. public static void main(String[] args) {
  4. SpringApplication.run(RaioXcapeBackend.class, args);
  5. }
  6. }

I know that the CORS configuration is not being applied because the API is allowing requests from any origin (e.g.: I send a GET request from my local running front-end), but my goal is to allow only from one origin, which is my deployed front-end application domain.

What could be happening? I've already checked the ${cors.allowed-origins}, and it's correct.

UPDATE 1

Below are the headers of a GET request to the API.

  1. Response Headers
  2. Cache-Control: no-cache, no-store, max-age=0, must-revalidate
  3. Connection: keep-alive
  4. Content-Type: application/json
  5. Date: Mon, 19 Jun 2023 22:58:41 GMT
  6. Expires: 0
  7. Keep-Alive: timeout=60
  8. Pragma: no-cache
  9. Transfer-Encoding: chunked
  10. Vary: Access-Control-Request-Headers
  11. Vary: Access-Control-Request-Method
  12. Vary: Origin
  13. X-Content-Type-Options: nosniff
  14. X-Frame-Options: DENY
  15. X-Xss-Protection: 0
  16. Request Headers
  17. Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7
  18. Accept-Encoding: gzip, deflate, br
  19. Accept-Language: en,pt;q=0.9
  20. Cache-Control: no-cache
  21. Connection: keep-alive
  22. Dnt: 1
  23. Host: localhost:8080
  24. Pragma: no-cache
  25. Sec-Ch-Ua: &quot;Not.A/Brand&quot;;v=&quot;8&quot;, &quot;Chromium&quot;;v=&quot;114&quot;, &quot;Google Chrome&quot;;v=&quot;114&quot;
  26. Sec-Ch-Ua-Mobile: ?0
  27. Sec-Ch-Ua-Platform: &quot;Windows&quot;
  28. Sec-Fetch-Dest: document
  29. Sec-Fetch-Mode: navigate
  30. Sec-Fetch-Site: none
  31. Sec-Fetch-User: ?1
  32. Upgrade-Insecure-Requests: 1
  33. User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36

答案1

得分: 1

在控制器级别上添加 @EnableWebMvc

将URL值放入 application.properties 中。

以下是您可以用作配置的代码:

  1. @Configuration
  2. @PropertySource("classpath:application.properties")
  3. public class SecurityConfiguration {
  4. @Autowired
  5. private Environment environment;
  6. @Bean
  7. public SecurityFilterChain securityFilterChain(HttpSecurity httpSecurity) throws Exception {
  8. return httpSecurity
  9. .csrf().disable().cors().configurationSource(this.corsConfigurationSource()).and()
  10. .authorizeHttpRequests().anyRequest().permitAll().and().build();
  11. }
  12. @Bean
  13. public CorsConfigurationSource corsConfigurationSource() {
  14. CorsConfiguration configuration = new CorsConfiguration();
  15. configuration.setAllowedOrigins(this.allowedOrigins);
  16. configuration.setAllowedMethods(Arrays.asList(
  17. HttpMethod.GET.name(), HttpMethod.POST.name(), HttpMethod.PUT.name(),
  18. HttpMethod.DELETE.name(), HttpMethod.HEAD.name(), HttpMethod.OPTIONS.name()
  19. ));
  20. configuration.setAllowedHeaders(Arrays.asList(
  21. HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, HttpHeaders.CONTENT_TYPE, HttpHeaders.ACCEPT,
  22. HttpHeaders.ORIGIN, HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, HttpHeaders.ACCESS_CONTROL_ALLOW_HEADERS,
  23. HttpHeaders.ACCESS_CONTROL_EXPOSE_HEADERS, HttpHeaders.AUTHORIZATION
  24. ));
  25. configuration.setExposedHeaders(Arrays.asList(
  26. HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD,
  27. HttpHeaders.ACCESS_CONTROL_ALLOW_HEADERS, HttpHeaders.ORIGIN, HttpHeaders.AUTHORIZATION
  28. ));
  29. configuration.setAllowCredentials(true);
  30. UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
  31. source.registerCorsConfiguration("/**", configuration);
  32. return source;
  33. }
  34. @Override
  35. public void addCorsMappings(CorsRegistry registry) {
  36. String origins = environment.getProperty("url");
  37. registry.addMapping("/v1/**")
  38. .allowedMethods("PATCH", "GET", "POST", "OPTIONS", "PUT", "DELETE")
  39. .allowedOrigins(origins.split(","))
  40. .allowedHeaders("*").allowCredentials(true);
  41. }
  42. }

这是您提供的代码的翻译部分。

英文:

Place @EnableWebMvc at Controller Level.

Place url value in application.properties

Below is the code that you can use as configuration.

  1. @Configuration
  2. @PropertySource(&quot;classpath:application.properties&quot;)
  3. public class SecurityConfiguration {
  4. @Autowired
  5. private Environment environment;
  6. @Bean
  7. public SecurityFilterChain securityFilterChain(HttpSecurity httpSecurity) throws Exception {
  8. return httpSecurity
  9. .csrf().disable().cors().configurationSource(this.corsConfigurationSource()).and()
  10. .authorizeHttpRequests().anyRequest().permitAll().and().build();
  11. }
  12. @Bean
  13. public CorsConfigurationSource corsConfigurationSource() {
  14. CorsConfiguration configuration = new CorsConfiguration();
  15. configuration.setAllowedOrigins(this.allowedOrigins);
  16. configuration.setAllowedMethods(Arrays.asList(
  17. HttpMethod.GET.name(), HttpMethod.POST.name(), HttpMethod.PUT.name(),
  18. HttpMethod.DELETE.name(), HttpMethod.HEAD.name(), HttpMethod.OPTIONS.name()
  19. ));
  20. configuration.setAllowedHeaders(Arrays.asList(
  21. HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, HttpHeaders.CONTENT_TYPE, HttpHeaders.ACCEPT,
  22. HttpHeaders.ORIGIN, HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, HttpHeaders.ACCESS_CONTROL_ALLOW_HEADERS,
  23. HttpHeaders.ACCESS_CONTROL_EXPOSE_HEADERS, HttpHeaders.AUTHORIZATION
  24. ));
  25. configuration.setExposedHeaders(Arrays.asList(
  26. HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD,
  27. HttpHeaders.ACCESS_CONTROL_ALLOW_HEADERS, HttpHeaders.ORIGIN, HttpHeaders.AUTHORIZATION
  28. ));
  29. configuration.setAllowCredentials(true);
  30. UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
  31. source.registerCorsConfiguration(&quot;/**&quot;, configuration);
  32. return source;
  33. }
  34. @Override
  35. public void addCorsMappings(CorsRegistry registry) {
  36. String origins = environment.getProperty(&quot;url&quot;);
  37. registry.addMapping(&quot;/v1/**&quot;)
  38. .allowedMethods(&quot;PATCH&quot;,&quot;GET&quot;, &quot;POST&quot;, &quot;OPTIONS&quot;,&quot;PUT&quot;, &quot;DELETE&quot;)
  39. .allowedOrigins(origins.split(&quot;,&quot;))
  40. .allowedHeaders(&quot;*&quot;).allowCredentials(true);
  41. }
  42. }

huangapple
  • 本文由 发表于 2023年6月19日 23:15:26
  • 转载请务必保留本文链接:https://go.coder-hub.com/76507961.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定