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

kyvafyod  于 5个月前  发布在  Spring
关注(0)|答案(1)|浏览(70)

这是我的CORSConfig类

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
@EnableWebMvc
public class CORSConfig{

    @Bean
    public WebMvcConfigurer corsConfigurer() {
        return new WebMvcConfigurer() {
            @Override
            public void addCorsMappings(CorsRegistry registry) {
                registry.addMapping("/**")
                        .allowedOrigins("*")
                        .allowedMethods("HEAD", "GET", "POST", "PUT", "DELETE", "PATCH", "OPTIONS")
                        .allowedHeaders("*")
                        .allowCredentials(false)
                        .maxAge(3600);
            }
        };
    }
}

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

@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
    http.csrf(csrf -> csrf.disable())
            .cors(httpSecurityCorsConfigurer ->
                    httpSecurityCorsConfigurer.configurationSource(request ->
                                    new CorsConfiguration().applyPermitDefaultValues()))
            .exceptionHandling(exception -> exception.authenticationEntryPoint(unauthorizedHandler))
            .sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
            .authorizeHttpRequests(auth ->
                    auth.requestMatchers("/api/auth/**").permitAll()
                            .requestMatchers("/swagger-ui/**", "/v3/api-docs/**").permitAll()
                            .requestMatchers("/api/test/**").permitAll()
                            .anyRequest().authenticated()
            );

    http.authenticationProvider(authenticationProvider());

    http.addFilterBefore(authenticationJwtTokenFilter(), UsernamePasswordAuthenticationFilter.class);

    return http.build();
}


我正在使用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

相关问题