繁体   English   中英

当我尝试从 angular 访问时,在 api 网关处出现 Cors 策略错误

[英]Getting Cors policy error at api gateway when i try to access from angular

When I try to access the microservice behind my API gateway through API gateway I am getting cors policy error for protected API but for unprotected API's it is working. 出于安全目的,我将 keycloak 用于受保护的 API 请求转移到带有令牌的 keycloak 但预检请求失败并显示“错误:重定向”

注意:后端代码按照 postman 中的要求工作正常,但问题出现在 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-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

有关 angular cli 代理的更多信息

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM