Chrome 访问由Google Cloud Run运行的Angular/Spring应用程序时获得403

irlmq6kh  于 2023-01-22  发布在  Go
关注(0)|答案(1)|浏览(132)

当我使用Google Chrome浏览器访问由Java Spring Boot应用程序托管的Angular应用程序时,Angular应用程序没有加载,但在Firefox中可以正常工作。
当我查看网络流量时,无法加载以下文件,并为它们返回403:

  • runtime.07055e28c13b1a74.js
  • polyfills.4e6aad8d16c34bbd.js
  • main.6cd67be9c6d2749b.js

CSS和字体文件(woff2)加载成功。
我使用Okta作为IAM(无需登录即可访问首页),但在我的Spring安全配置中,我已配置为允许访问所有JS文件:

http.authorizeRequests()
    .antMatchers("/", "/index.html", "/**.js", "/**.css").permitAll()

Google Cloud Run中的应用程序成功启动。但在Google Cloud Run的日志中,我看到以下警告(上面提到的3个js文件各一个):

{
httpRequest: {
latency: "0.011511853s"
protocol: "HTTP/1.1"
referer: "<my-address>"
remoteIp: "<remote-ip>"
requestMethod: "GET"
requestSize: "1178"
requestUrl: "<my-address>/main.6cd67be9c6d2749b.js"
responseSize: "716"
serverIp: "<server-ip>"
status: 403
userAgent: "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/108.0.0.0 Safari/537.36"
}
insertId: "639f77b8000c61e0d23eef65"
labels: {1}
logName: "projects/original-advice-xxx/logs/run.googleapis.com%2Frequests"
receiveTimestamp: "2022-12-18T20:27:37.049604375Z"
resource: {2}
severity: "WARNING"
spanId: "4738744206884247185"
timestamp: "2022-12-18T20:27:36.811488Z"
trace: "projects/original-advice-xxx/traces/257d4794b443727cf7d37d1a0863e682"
traceSampled: true
}

在Google Chrome浏览器的控制台中,将打印以下错误:

...-ew.a.run.app/:12          GET https://...-ew.a.run.app/polyfills.4e6aad8d16c34bbd.js net::ERR_ABORTED 403
...-ew.a.run.app/:12          GET https://...-ew.a.run.app/main.6cd67be9c6d2749b.js net::ERR_ABORTED 403
...-ew.a.run.app/:12          GET https://...-ew.a.run.app/runtime.07055e28c13b1a74.js net::ERR_ABORTED 403

当我在本地运行应用程序时,这3个文件可以在Chrome中成功加载。
我在Google Cloud Run中的配置:

  • 入口:允许所有流量
  • 认证:允许未经身份验证的请求(对于公共API或网站)

我也试过:

gcloud run services add-iam-policy-binding <my-service> --member="allUsers" --role="roles/run.invoker"

有人知道为什么这3 JS文件不能正确加载谷歌浏览器?

zu0ti5jz

zu0ti5jz1#

将应用程序域(应用程序在Google Cloud Run中运行的地方)添加到Sping Boot CORS允许的来源列表解决了这个问题。

@Bean
  public FilterRegistrationBean<CorsFilter> simpleCorsFilter() {
    var source = new UrlBasedCorsConfigurationSource();
    var config = new CorsConfiguration();
    config.setAllowCredentials(true);
    // also add origins to auth.interceptor.ts and to Okta trusted Origins (Security -> API)
    // also see: https://developer.okta.com/docs/guides/enable-cors/main/
    config.addAllowedOrigin("http://localhost:4200");
    config.addAllowedOrigin("https://xxx-ew.a.run.app");
    config.addAllowedMethod("*");
    config.addAllowedHeader("*");
    source.registerCorsConfiguration("/**", config);
    var bean = new FilterRegistrationBean<>(new CorsFilter(source));
    bean.setOrder(Ordered.HIGHEST_PRECEDENCE);
    return bean;
  }

相关问题