如何使用 Swagger 在 API 网关上全局设置 API 密钥安全

How can I set API Key Security Globally on API Gateway using Swagger

我正在尝试将 openapi/swagger 文件导入 api 网关,但我无法获得预期的安全设置。我想要所有路径都需要一个 api 密钥。

设置它 api 导入后在控制台中需要的密钥有效,但这种解决方案是不可取的,同样有效的是在每个路径中单独设置安全字段,但我正在寻找一个全局解决方案。

当我尝试导入文件时收到以下警告:

Your API was not imported due to errors in the Swagger file.

    Method 'GET' on resource '/' specified security,
    but no custom authorizers were created and the extension
    x-amazon-apigateway-auth was not set.
    This method will be not be secured. 

看起来,我需要一个 lambda 作为 api 键的自定义授权者(我不熟悉授权者,但如果我不这样做,这似乎没有意义在控制台中设置 api 键时不需要一个);或者我需要对这个神秘的 x-amazon-apigateway-auth 做些什么,我找不到文档(所有其他 openapi 扩展亚马逊已经记录 here)。

下面是一个最小的例子:

openapi: 3.0.1
info:
  title: test
  version: 0
servers:
- url: "/"
security:
  - ApiKey: []
paths:
  "/":
    get:
      # if I copy the security part into here things work 
      responses:
        '204':
          description: no content
      x-amazon-apigateway-integration:
        httpMethod: GET
        type: http
        uri: https://httpstat.us/204
components:
  securitySchemes:
    ApiKey:
      type: apiKey
      name: x-api-key
      in: header
x-amazon-apigateway-api-key-source: HEADER

因为 api 密钥安全设置在根级别,这向我建议所有路径都应该使用 api 密钥(除非被个别路径覆盖),实际发生的是上面的警告,导入时不需要 api 密钥。

在我写这个答案时,根据他们的 documentation,AWS API 网关不支持在根级别设置安全性。

API Gateway doesn't use root level security defined in the OpenAPI specification. Hence security needs to be defined at an operation level to be appropriately applied.