这是我的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的老问题的答案,也尝试与谷歌。也与我的队友协调,但没有成功。
1条答案
按热度按时间bmvo0sr51#
您正在使用
applyPermitDefaultValues
,因此仅设置默认值,请参阅CorsConfiguration
:applyPermitDefaultValues
public CorsConfiguration applyPermitDefaultValues()
个默认情况下,
CorsConfiguration
不允许任何跨域请求,必须显式配置。使用此方法可以切换到允许GET、HEAD和POST的所有跨域请求的默认值,但不覆盖任何已设置的值。以下默认值适用于未设置的值:您必须相应地配置自定义
CorsConfiguration
。这就是CORS。