这是我的 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);
}
};
}
}
这个Bean我已经在SecurityConfig.java中定义了
@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();
}
我使用的是 spring boot 3.1.6、spring-security 6.1.5 和 JDK 17。以上配置我用来处理 CORS。当我在 server 上测试 Postman 和 Swagger 的 API 时,效果很好。
但是当我在前端集成react.js然后GET、POST方法工作正常,但对于PUT方法,这会给出请求的资源上不存在“Access-Control-Allow-Origin”标头错误。
我已经尝试了 stackoverflow 上有关此问题的旧问题的答案,并尝试使用 Google。也和队友协调但没有成功。
您使用的是
applyPermitDefaultValues
,因此仅设置了默认值,请参阅 CorsConfiguration
:
应用PermitDefaultValues
public CorsConfiguration applyPermitDefaultValues()
默认情况下
不允许任何跨域请求,必须显式配置。使用此方法切换到允许 GET、HEAD 和 POST 的所有跨域请求的默认值,但不会覆盖任何已设置的值。 以下默认值适用于未设置的值:CorsConfiguration
- 允许所有具有 CORS 规范中定义的特殊值“*”的来源。仅当 origins 和 originPatterns 均未设置时才设置。
- 允许“简单”方法 GET、HEAD 和 POST。
- 允许所有标头。
- 将最大年龄设置为 1800 秒(30 分钟)。
您必须相应地配置您的自定义
CorsConfiguration
。