【问题标题】:Express Gateway CORS + apiKey authorization 401 UnauthorizedExpress Gateway CORS + apiKey 授权 401 Unauthorized
【发布时间】:2019-07-24 17:02:45
【问题描述】:

意图

CORS 配置似乎有效且有效,在 React-App 中我可以轻松访问网关。也可以通过 Postman 访问,所以 apiKey 不会导致问题。

但如果我使用 apiKey 添加身份验证,我会在所有浏览器中收到错误消息。 在 Chrome 中:

问题

选项https://example-gateway.com/test 401 (未经授权)

访问 XMLHttpRequest 在 'https://example-gateway.com/test' 来自原点 'https://example-app.com' 已被 CORS 阻止 策略:对预检请求的响应未通过访问控制 检查:它没有 HTTP ok 状态。

是什么导致了这种行为?浏览器是否没有通过 OPTIONS-CORS 请求发送所需的 apiKey 并因此被阻止?

如何解决?

代码

pipelines:
  adminAPI:
    apiEndpoints:
      - testApi
    policies:
      - cors:
          - action:
              origin: [https://example-gateway.com]
              methods: GET,POST,PUT,DELETE,OPTIONS
              preflightContinue: true
              optionsSuccessStatus: 204
              credentials: true
              maxAge: 600
              allowedHeaders:
                - Authorization
              exposedHeaders:
                - Authorization
      - key-auth:
          - action:
              apiKeyHeader: Authorization
              disableHeadersScheme: false
      - proxy:
          - action:
              serviceEndpoint: testBackend

【问题讨论】:

    标签: cors express-gateway


    【解决方案1】:

    我认为问题在于 key-auth 为 CORS 的 OPTION 调用返回 401,这就是您可能收到此类问题的原因。

    您很可能可以通过在 key-auth 调用中添加条件来解决此问题。

    http:
      port: ${EG_HTTP_PORT:-8080}
    # https:
    #   port: 9999
    #   tls: {}
    admin: # remove this section to disable admin API
      port: 9876
      host: localhost # use 0.0.0.0 to listen on all IPv4 interfaces
    apiEndpoints:
      api:
        host: '*'
    serviceEndpoints:
      backend:
        url: 'http://localhost:9876' # btw this is EG admin API
    policies:
      - proxy
      - key-auth
      - cors
    pipelines:
      adminAPI:
        apiEndpoints:
          - api
        policies:
          - cors:
          - key-auth:
            - condition:
                name: not
                condition:
                  name: method
                  methods:
                    - OPTIONS
            action:
              apiKeyHeader: Authorization
              disableHeadersScheme: false
          - proxy:
              action:
                serviceEndpoint: backend
    
    

    【讨论】:

    • 你能看一下吗?另一个提示会很棒,谢谢!
    • 感谢您的示例。我复制了它,但仍然得到错误。你测试成功了吗,你确定它是这样工作的吗?
    • 我做到了!你还在面对这个问题吗?这很奇怪。
    • 好的,那么我想很可能我的 yaml 文件中有一些缩进错误,即使在日志中没有错误。我去看看,谢谢。
    • 现在可以了!怀疑是缩进错误。作为使 Express Gateway 更易于使用的建议:a)在文档中包含此示例,我认为这是一个常见用例 b)如果配置不完全工作,EG 应在日志中输出错误无论如何:谢谢感谢您的帮助,继续努力!
    猜你喜欢
    • 2017-03-16
    • 2016-12-04
    • 1970-01-01
    • 2014-11-10
    • 2020-03-24
    • 2017-09-20
    • 2020-05-28
    • 2021-01-08
    • 2016-09-13
    相关资源
    最近更新 更多