跨源PATCH和DELETE请求被Spring Boot应用程序阻止,但不包括GET请求



目前,我的Spring Boot应用程序中有以下安全配置。这是我在网上找到的允许所有COR请求的标准配置(我也在网上尝试过很多其他配置(。

这些对GET请求很有效,但是由于CORs策略,PATCH和DELETE请求仍然被阻止。以前有人经历过这种情况吗?

@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.cors().configurationSource(request -> new CorsConfiguration().applyPermitDefaultValues());
}
}

您可以使用addAllowedMethod在默认允许的方法(GET、HEAD、POST(中添加其他方法

CorsConfiguration corsConfig = new CorsConfiguration().applyPermitDefaultValues();
corsConfig.addAllowedMethod(HttpMethod.DELETE);
corsConfig.addAllowedMethod(HttpMethod.PUT);
http.cors().configurationSource(request -> corsConfig);

是的,所以我用下面的配置解决了这个问题,但有一点需要注意:我以前尝试过,但我对CorsFilter的第一个导入建议不是正确的(org.apache.catalina.filters.CorsFilter(。这一次,我导入了第二个(org.springframework.web.filters.CorsFilter(,现在可以了。

@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.cors().and().csrf().disable();
}

@Configuration
public class CorsConfig {
@Bean
public CorsFilter corsFilter() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
CorsConfiguration config = new CorsConfiguration();
config.setAllowCredentials(true);
config.addAllowedOrigin("http://localhost:3000");
config.addAllowedHeader("*");         
config.addAllowedMethod("POST");
config.addAllowedMethod("GET");
config.addAllowedMethod("PATCH");
source.registerCorsConfiguration("/**", config);
return new CorsFilter(source);
}
}
}

您可以通过创建以下bean 来添加对CORS的全局支持

@Bean
public WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurer() {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**").allowedOrigins("*");
}
};
}

在更新版本的Spring Security上,如果您查看CorsRegistration allowedMethods((,您将看到

/**
* Set the HTTP methods to allow, e.g. {@code "GET"}, {@code "POST"}, etc.
* <p>The special value {@code "*"} allows all methods.
* <p>By default "simple" methods {@code GET}, {@code HEAD}, and {@code POST}
* are allowed.
*/
public CorsRegistration allowedMethods(String... methods) {
this.config.setAllowedMethods(Arrays.asList(methods));
return this;
}

默认情况下,只允许使用GET、HEAD和POST。

正在添加其他方法或全部。。。可能看起来像这个

@Profile(value = { "LOCAL" })
@Configuration
public class CorsConfig {
@Bean
public WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurer() {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry
.addMapping("/**")
.allowedMethods("*") <-- This is the ticket
.allowedOrigins("*")
;
}
};
}
}

应该做的技巧

最新更新