Spring Boot 在Sping Boot 3中请求的资源上不存在“Control-Allow-Origin”标头

kyvafyod  于 2024-01-06  发布在  Spring
关注(0)|答案(1)|浏览(153)

这是我的CORSConfig类

  1. import org.springframework.context.annotation.Bean;
  2. import org.springframework.context.annotation.Configuration;
  3. import org.springframework.web.servlet.config.annotation.CorsRegistry;
  4. import org.springframework.web.servlet.config.annotation.EnableWebMvc;
  5. import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
  6. @Configuration
  7. @EnableWebMvc
  8. public class CORSConfig{
  9. @Bean
  10. public WebMvcConfigurer corsConfigurer() {
  11. return new WebMvcConfigurer() {
  12. @Override
  13. public void addCorsMappings(CorsRegistry registry) {
  14. registry.addMapping("/**")
  15. .allowedOrigins("*")
  16. .allowedMethods("HEAD", "GET", "POST", "PUT", "DELETE", "PATCH", "OPTIONS")
  17. .allowedHeaders("*")
  18. .allowCredentials(false)
  19. .maxAge(3600);
  20. }
  21. };
  22. }
  23. }

字符串
我在SecurityConfig.java中定义了这个Bean

  1. @Bean
  2. public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
  3. http.csrf(csrf -> csrf.disable())
  4. .cors(httpSecurityCorsConfigurer ->
  5. httpSecurityCorsConfigurer.configurationSource(request ->
  6. new CorsConfiguration().applyPermitDefaultValues()))
  7. .exceptionHandling(exception -> exception.authenticationEntryPoint(unauthorizedHandler))
  8. .sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
  9. .authorizeHttpRequests(auth ->
  10. auth.requestMatchers("/api/auth/**").permitAll()
  11. .requestMatchers("/swagger-ui/**", "/v3/api-docs/**").permitAll()
  12. .requestMatchers("/api/test/**").permitAll()
  13. .anyRequest().authenticated()
  14. );
  15. http.authenticationProvider(authenticationProvider());
  16. http.addFilterBefore(authenticationJwtTokenFilter(), UsernamePasswordAuthenticationFilter.class);
  17. return http.build();
  18. }


我正在使用Sping Boot 3.1.6,Spring-Security 6.1.5和JDK 17。上面的配置我已经用来处理CORS。当我在server上测试Postman和Swagger的API时,这工作正常。
但是当我在前端集成react.js,然后GET,POST方法工作正常,但对于PUT方法,这给出了 No 'Node-Control-Allow-Origin' header is present on the requested resource 错误。
我已经尝试了关于stackoverflow的老问题的答案,也尝试与谷歌。也与我的队友协调,但没有成功。

bmvo0sr5

bmvo0sr51#

您正在使用applyPermitDefaultValues,因此仅设置默认值,请参阅CorsConfiguration

applyPermitDefaultValues

public CorsConfiguration applyPermitDefaultValues()
默认情况下,CorsConfiguration不允许任何跨域请求,必须显式配置。使用此方法可以切换到允许GET、HEAD和POST的所有跨域请求的默认值,但不覆盖任何已设置的值。以下默认值适用于未设置的值:

  • 允许所有在CORS规范中定义了特殊值“*”的原点。只有在既没有设置原点也没有设置原点模式时才设置此值。
  • 允许“简单”方法GET、HEAD和POST。
  • 允许所有标题。
  • 将最大年龄设置为1800秒(30分钟)。

您必须相应地配置自定义CorsConfiguration
这就是CORS

相关问题