首页 > 解决方案 > 带有 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.

有小费吗?

谢谢。

标签: spring-bootgoogle-app-enginecors

解决方案


我使用了这段代码:参考:https ://blogs.ashrithgn.com/disable-cors-in-spring-boot/ 我有两个 GAE 项目

  1. 基于 Python 使用 Angular 11
  2. 基于 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;
}

推荐阅读