带有Spring Boot CORS的App Engine Standard不起作用

时间:2019-10-25 18:20:47

标签: spring-boot google-app-engine cors

我正在实现一个托管在Google App Engine标准环境中的Spring Boot应用程序。

我在the official guide之后配置了这样的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.

有什么提示吗?

谢谢。

2 个答案:

答案 0 :(得分:0)

我认为您错过了cors中重要部分的设置标题。

添加此行

configuration.allowedHeaders = listOf("*")

答案 1 :(得分:0)

我使用了这个代码: 参考: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/ 会有所作为

@配置 公共类 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;
}