Spring Boot 2.4.0 版本中 CORS 策略的更改

mis*_*r42 5 java spring cors spring-boot

使用 Spring 2.3.0.RELEASE 我有以下 CORS 配置:

@Configuration
@EnableWebSecurity
@ComponentScan("com.softeq.ems.config")
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class EmsJwtSecurityConfig extends BaseSecurityConfig {

    @Value("${management.endpoints.web.cors.allowed-origins}")
    private String[] allowedOrigins;

    @Override
    protected void configureHttp(HttpSecurity http) throws Exception {
        if (allowedOrigins.length > 0) {
            http.cors().configurationSource(corsConfigSource());
        }

        http.csrf().disable();
    }

    private CorsConfigurationSource corsConfigSource() {

        final CorsConfiguration corsConfig = new CorsConfiguration();
        corsConfig.addAllowedHeader(CorsConfiguration.ALL);
        corsConfig.addAllowedMethod(CorsConfiguration.ALL);

        Stream.of(allowedOrigins).forEach(
            origin -> corsConfig.addAllowedOrigin(origin)
        );

        return request -> corsConfig;
    }
Run Code Online (Sandbox Code Playgroud)

多变的 management.endpoints.web.cors.allowed-origins = http://localhost:4200, http://127.0.0.1:4200

这个配置运行良好,我需要的所有跨平台请求都得到了授权。

但是在发布后迁移到spring-boot 2.4.0后,当我像往常一样尝试向主机发送请求时,在chrome浏览器控制台中出现了经典的cors策略错误:

Access to XMLHttpRequest at 'http://localhost:8080/api/v1/me/balance' from origin 'http://localhost:4200' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status
Run Code Online (Sandbox Code Playgroud)

Spring 发行说明说 cors 配置提供了一个新属性allowedOriginPatterns,但我不明白如何使用它:https : //github.com/spring-projects/spring-framework/wiki/What%27s-New-in- Spring-Framework-5.x#general-web-revision

请帮我弄清楚我的问题是什么!

Yaz*_*dEF 5

我将对您的代码执行以下操作:

private CorsConfigurationSource corsConfigSource() {

    final CorsConfiguration corsConfig = new CorsConfiguration();
    corsConfig.addAllowedHeader(CorsConfiguration.ALL);
    corsConfig.addAllowedMethod(CorsConfiguration.ALL);

    Stream.of(allowedOrigins).forEach(
        //origin -> corsConfig.addAllowedOrigin(origin)
        origin -> corsConfig.addAllowedOriginPattern(origin)
    );

    return request -> corsConfig;
}
Run Code Online (Sandbox Code Playgroud)


Dmi*_*ich 1

我是这样做的:

@Configuration
@Profile("!production")
class CorsConfig : WebMvcConfigurer {
    override fun addCorsMappings(registry: CorsRegistry) {
        registry
            .addMapping("/**")
            .allowedOriginPatterns("http://localhost:3000")
    }
}
Run Code Online (Sandbox Code Playgroud)