spring-boot - 带有 Spring Boot CORS 的 App Engine Standard 无法正常工作
问题描述
我正在实现一个托管在 Google App Engine 标准环境上的 Spring Boot 应用程序。
我按照官方指南配置了这样的CORS :
@Configuration
@EnableWebSecurity
class WebSecurityConfigurer : WebSecurityConfigurerAdapter() {
@Throws(Exception::class)
override fun configure(http: HttpSecurity) {
http.csrf()
.disable()
.cors()
.and().sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and().authorizeRequests().antMatchers("/api/**").permitAll()
}
@Bean
fun corsConfigurationSource(): CorsConfigurationSource {
val configuration = CorsConfiguration()
configuration.allowedOrigins = listOf("*")
configuration.allowedMethods = listOf("GET", "POST", "OPTIONS", "PUT", "DELETE", "HEAD")
val source = UrlBasedCorsConfigurationSource()
source.registerCorsConfiguration("/**", configuration)
return source
}
执行以下 cURL 我收到 AllowedOrigins 标头,因为它是必要的:
curl -H "Access-Control-Request-Method: GET" -H "Origin: http://foo" -X OPTIONS "localhost:8080/api/abc/list?lang=de"
回复:
HTTP/1.1 200
Access-Control-Allow-Origin: *
现在,当我将 Spring App 部署到 AppEngine 时,我也可以成功地 cURL。
HTTP/2 200
access-control-allow-origin: https://myfrontend.com
access-control-allow-methods: GET
access-control-allow-credentials: true
不幸的是,我的前端应用程序被 403 阻止
Access to fetch at 'https://mybackend.com/api/abc/list?lang=de' from origin 'https://myfrontend.com' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
有小费吗?
谢谢。
解决方案
我使用了这段代码:参考:https ://blogs.ashrithgn.com/disable-cors-in-spring-boot/ 我有两个 GAE 项目
- 基于 Python 使用 Angular 11
- 基于 Spring Boot 的微服务标准环境
Imp:app.yaml 中的任何其他更改或 spring 在 https://spring.io/guides/gs/rest-service-cors/中提到的不会有任何不同
@Configuration 公共类 CorsConfig {
@Bean
public FilterRegistrationBean corsFilter() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
CorsConfiguration config = new CorsConfiguration();
config.setAllowCredentials(true);
config.addAllowedOrigin("*");
config.addAllowedHeader("*");
config.addAllowedMethod("*");
source.registerCorsConfiguration("/**", config);
FilterRegistrationBean bean = new FilterRegistrationBean(new CorsFilter(source));
bean.setOrder(0);
return bean;
}
推荐阅读
- c - 未解析的外部符号 bcrypt_gensalt
- reactjs - 如何使用 react-pdf 库创建表格以生成 pdf 报告?
- windows - 如何批量获取未识别的网络适配器名称
- gpu - 关于 docker、nvidia-docker、cudnn 和 tensorflow 的问题
- rust - 如何为特征提供 IntoIterator 的默认实现?
- c# - 在 MEF 中的泛型方法中转换类
- html - 我的浏览器中仍然显示隐藏的列,这是什么问题?
- vue.js - 如何将垂直“b-tabs”导航部分和内容部分的高度设置为相同(基于内容部分)
- function - 在 Go 中是否可以使用命名参数调用函数?
- label - 使用python在Gtk中的标签内垂直居中文本