gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 23:02:16 27 4
gpt4 key购买 nike

使用 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;
}
变量 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
Spring 发行说明说 cors 配置提供了一个新属性 allowedOriginPatterns ,但我不明白如何使用它:
https://github.com/spring-projects/spring-framework/wiki/What%27s-New-in-Spring-Framework-5.x#general-web-revision
请帮我弄清楚我的问题是什么!

最佳答案

这里我会对你的代码做些什么:

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;
}

关于java - Spring Boot 2.4.0 版本中 CORS 策略的更改,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64893796/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com