在 Amazon API 网关中使用 API 密钥

Using an API key in Amazon API Gateway

我创建了一个 API 密钥并将其添加到我的函数中。然后我部署了 api 并对其进行了测试,但仍然得到:

"message": "Forbidden"

如何在我的 JSON 请求中传递 api 密钥,因为我一直在使用 "x-api-key": "theKey"?

希望您不会错过 link API 键和 API

x-api-key 参数作为 HTTP header 参数传递(即它不会添加到 JSON body)。您如何传递 HTTP headers 取决于您使用的 HTTP 客户端。

例如,如果您使用 curl 并假设您 POST 是 JSON 有效载荷,请求将类似于(您将 [api-id] 替换为实际 ID 和 [region] 与您 API 的 AWS 区域):

$ curl -X POST -H "x-api-key: theKey" -H "Content-Type: application/json" -d '{"key":"val"}' https://[api-id].execute-api.[region].amazonaws.com

我必须添加一个 API 使用计划,然后 link 该计划进入 API 阶段。

似乎这是 link API 密钥的唯一方法,不确定这是否是 AWS 最近的更改。

如果您将 'API Key Required' 选项设置为 true,请检查以下内容。

  1. 您必须将 'x-api-key' HTTP Header 参数传递给 API 网关。

  2. 必须创建 API 密钥。

  3. 此外,您需要检查 API 网关控制台上 API 键的使用计划。

如果将 'API' key required 设置为 true,则需要将 api key 作为 header 传递。

API 密钥作为 header 字段 'x-api-key' 传递。即使在 header 中添加此字段后,也可能会出现此问题。在这种情况下,请验证以下几点

  1. 你有使用计划吗?如果不需要就创建一个。
  2. Link 你 API 有使用计划。为此添加一个阶段,它将 link 你的 API
  3. 你有 API 密钥吗?如果不是,您需要创建一个 API 密钥并启用它。
  4. 将使用您的 API link 编辑的使用计划添加到此 API 键。为此,添加使用计划。

对于通过 public DNS 访问的私有 API 网关,我们需要通过 api id 和 'x-api-key' 如果已配置。

curl -v https://{vpce-id}.execute-api.{region}.vpce.amazonaws.com/test -H 'x-apigw-api-id:{api-id}'

其记录如下,

https://docs.aws.amazon.com/apigateway/latest/developerguide/apigateway-private-api-test-invoke-url.html#w20aac13c16c28c11

我能够在 Postman 本机应用程序中使用以下配置从 Lambda 获得成功响应 -

在授权选项卡下(出于某种原因,当我在 header 下传递相同的参数时这不起作用)

密钥:x-api-key

值:your-api-key-value

添加到:Header

我没有足够的声誉将其设置为评论,但我终于找到了指定 'x-api-key' 属于 header 的文档 API 网关AWS 文档中来自外部客户端(如邮递员、swagger 等)的调用。

相关部分:

To use header-sourced API keys:

  1. Create an API with desired API methods. And deploy the API to a stage.
  2. Create a new usage plan or choose an existing one. Add the deployed API stage to the usage plan. Attach an API key to the usage plan or choose an existing API key in the plan. Note the chosen API key value.
  3. Set up API methods to require an API key.
  4. Redeploy the API to the same stage. If you deploy the API to a new stage, make sure to update the usage plan to attach the new API stage.

The client can now call the API methods while supplying the x-api-key header with the chosen API key as the header value.

Choose an API key source

Here a good resource 解释我们可能会收到 Forbidden 的不同原因。最重要的两个是 请求 URLx-api-key header:

https://{api_id}.execute-api.{region}.amazonaws.com/{stage_name}/{resource_name}

缺少艺名会给你 403 for ex.也许出于安全原因,响应没有揭示舞台名称的问题,因此您得到一个通用的 Forbidden.