Spring Cloud API 网关和 OAuth2 服务器没有“访问控制允许来源”

问题描述 投票:0回答:1

在使用 Spring Cloud API Gateway 和 Spring Security OAuth2 服务器时,我遇到了 CORS 问题。由于响应中缺少 Access-Control-Allow-Origin 标头,我在 http://localhost:4200/ 上运行的前端应用程序被阻止。 “已被 CORS 策略阻止:对预检请求的响应未通过访问控制检查:请求的资源上不存在“Access-Control-Allow-Origin”标头。”

我已经在 application.yaml 文件中使用以下设置配置了 CORS:

spring:
  cloud:
    gateway:
      globalcors:
        cors-configurations:
          '[/**]':
            allowedOrigins: "http://localhost:4200"
            allowedMethods: '*'
            allowedHeaders: '*'
    security:
      oauth2:
        resourceserver:
          jwt:
            issuer-uri: https://securetoken.google.com/<project-id>
            jwk-set-uri: https://www.googleapis.com/service_accounts/v1/jwk/[email protected]

尽管进行了上述配置,我仍然遇到 CORS 错误。有人可以帮助我确定此行为的潜在原因并建议进一步的故障排除步骤来解决该问题吗?

如果不使用 oauth2 资源服务器依赖项,我不会出现任何 CORS 错误。

如何在不使用 api 网关的情况下确保我的微服务安全?目前,当我不使用 api 网关来处理我的请求时,我无需进行身份验证并有权访问所有端点。

spring spring-boot cors spring-cloud-gateway spring-resource-server
1个回答
0
投票

“CORS 必须在 Spring Security 之前处理,因为预检请求不会包含任何 cookie(即 JSESSIONID)。如果请求不包含任何 cookie 并且 Spring Security 优先,则该请求将确定用户未经过身份验证(因为请求中没有 cookie)并拒绝它。”

https://docs.spring.io/spring-security/reference/reactive/integrations/cors.html

© www.soinside.com 2019 - 2024. All rights reserved.