【问题标题】:Getting Cors policy error at api gateway when i try to access from angular当我尝试从角度访问时,在 api 网关上出现 Cors 策略错误
【发布时间】:2023-04-06 13:00:01
【问题描述】:

当我尝试通过 API 网关访问我的 API 网关后面的微服务时,我收到受保护 API 的 cors 策略错误,但对于不受保护的 API,它正在工作。 出于安全目的,我使用 keycloak 将受保护的 API 请求转移到带有令牌的 keycloak 但预检请求失败并显示“错误:重定向”

注意:后端代码按照邮递员的要求工作正常,但问题出现在 Angular 前端

以下代码分别用于 API 网关 yaml 设置和安全配置:

>     app:
> 
>   config:
> 
>     keycloak:
> 
>       url: http://localhost:8180/auth
> 
>       realm: master
> 
>      
> 
> server:
> 
>   port: 8085
> 
>  
> 
> eureka:
> 
>   client:
> 
>     registerWithEureka: true
> 
>     fetchRegistry: true
> 
>     serviceUrl:
> 
>       defaultZone: http://localhost:8084/eureka/
> 
>  
> 
> spring:
> 
>   application:
> 
>     name: apigateway
> 
>   cloud:
> 
>     # A client sends a request to Spring Cloud Gateway. If the request matches a route through its predicates, the Gateway HandlerMapping
> will send the request to the Gateway WebHandler, which in turn will
> run the request through a chain of filters.
> 
>     gateway:
> 
>       **default-filters:
> 
>         - DedupeResponseHeader=Access-Control-Allow-Credentials Access-Control-Allow-Origin Access-Control-Allow-Headers
> 
>       globalcors:
> 
>         corsConfigurations:
> 
>           '[/**]':
> 
>             allowedOrigins: "*"
> 
>             allowedMethods: "*"
> 
>             allowedHeaders: "*"
>** 
>       # For automatic route discovery through Eureka
> 
>       discovery.locator:
> 
>         enabled: false
> 
>         lowerCaseServiceId: true
> 
>       # Route. It’s identified by a unique ID, a collection of predicates deciding whether to follow the route, a URI for forwarding
> the request if the predicates allow, and a collection of filters
> applied either before or after forwarding the request downstream.
> 
>       routes:
> 
>         - id: adminmodule
> 
>           uri: lb://adminms
> 
>           predicates:
> 
>             - Path=/adminapi/**
> 
>           filters:
> 
>             - RewritePath=/adminapi/(?<path>.*), /$\{path}
> 
>         - id: appointmentmodule
> 
>           uri: lb://appointmentms
> 
>           predicates:
> 
>             - Path=/appointmentapi/**
> 
>           filters:
> 
>             - RewritePath=/appointmentapi/(?<path>.*), /$\{path}
> 
>         - id: inboxmodule
> 
>           uri: lb://inboxms
> 
>           predicates:
> 
>             - Path=/inboxapi/**
> 
>           filters:
> 
>             - RewritePath=/inboxapi/(?<path>.*), /$\{path}
> 
>         - id: patientmodule
> 
>           uri: lb://patientms
> 
>           predicates:
> 
>             - Path=/patientapi/**
> 
>           filters:
> 
>             - RewritePath=/patientapi/(?<path>.*), /$\{path}
> 
>         - id: staticurl
> 
>           uri: http://localhost:8081
> 
>           predicates:
> 
>             - Path=/static-url/**
> 
>           filters:
> 
>             - RewritePath=/static-url/(?<path>.*), /$\{path}
> 
>        
> 
>   security:
> 
>     oauth2:
> 
>       client:
> 
>         provider:
> 
>           keycloak:
> 
>             token-uri: ${app.config.keycloak.url}/realms/${app.config.keycloak.realm}/protocol/openid-connect/token
> 
>             authorization-uri: ${app.config.keycloak.url}/realms/${app.config.keycloak.realm}/protocol/openid-connect/auth
> 
>             user-name-attribute: preferred_username
> 
>             user-info-uri: ${app.config.keycloak.url}/realms/${app.config.keycloak.realm}/protocol/openid-connect/userinfo
> 
>             jwk-set-uri: ${app.config.keycloak.url}/realms/${app.config.keycloak.realm}/protocol/openid-connect/certs
> 
>             user-info-authentication-method: header
> 
>         registration:
> 
>           apigateway:
> 
>             provider: keycloak
> 
>             client-id: apigateway
> 
>             client-secret: 7F8DqfFeTWxYv9pkvfrZ1XAxc2udVS0X
> 
>             authorization-grant-type: authorization_code
> 
>             redirect-uri: http://localhost:8180/login/oauth2/code/keycloak
> 
>             scope: openid
> 
>       resourceserver:
> 
>         jwt:
> 
>           jwk-set-uri: ${app.config.keycloak.url}/realms/${app.config.keycloak.realm}/protocol/openid-connect/certs
> 
> 
> management:
> 
>   endpoints:
> 
>     web:
> 
>       exposure:
> 
>         include: '*'
> 
> logging:
> 
>   level:
> 
>     com.netflix: WARN
> 
>     org.springframework.web: DEBUG
> 
>     com.edu: DEBUG

安全 java 文件:

@CrossOrigin(maxAge=3600)

@EnableWebFluxSecurity

@EnableReactiveMethodSecurity

public class SecurityConfiguration  {

       @Bean

       public SecurityWebFilterChain securityWebFilterChain(ServerHttpSecurity http) {

 

              http.authorizeExchange()

//ALLOWING REGISTER API FOR DIRECT ACCESS

                           .pathMatchers("/adminapi/login/**").permitAll()

//ALL OTHER APIS ARE AUTHENTICATED

                           .anyExchange().authenticated().and().

                           csrf().disable().oauth2Login().

                           and().oauth2ResourceServer().jwt();

             

              http.cors();

              return http.build();

       }

 
}

我尝试了互联网上几乎所有可能的解决方案,但没有任何解决方案适合我。 请帮忙。

【问题讨论】:

    标签: angular spring-boot cors microservices api-gateway


    【解决方案1】:

    您是否从 angular-cli 设置了代理配置?

    通过将文件传递给 --proxy-config 构建选项,使用 webpack 开发服务器中的代理支持将某些 URL 转移到后端服务器。例如,要将所有对 http://localhost:4200/api 的调用转移到运行在 http://localhost:3000/api 上的服务器,请执行以下步骤。

    1. 在项目的src/ 文件夹中创建一个文件proxy.conf.json
    2. 将以下内容添加到新的代理文件中:
    {
      "/api": {
        "target": "http://localhost:3000",
        "secure": false
      }
    }
    
    1. 在 CLI 配置文件 angular.json 中,将 proxyConfig 选项添加到 serve 目标:
    ...
    "architect": {
      "serve": {
        "builder": "@angular-devkit/build-angular:dev-server",
        "options": {
          "browserTarget": "your-application-name:build",
          "proxyConfig": "src/proxy.conf.json"
        },
    ...
    
    1. 要使用此代理配置运行开发服务器,请致电ng serve

    more information about angular cli proxy

    【讨论】:

    • 试过了,问题依旧
    猜你喜欢
    • 2020-01-19
    • 1970-01-01
    • 2021-10-30
    • 2021-11-11
    • 2021-09-24
    • 2021-09-05
    • 2019-12-25
    • 2023-02-01
    • 1970-01-01
    相关资源
    最近更新 更多