AWS API 从 Lambda 调用时网关 403 被禁止

AWS API Gateway 403 Forbidden when calling from Lambda

我有一个带有 IAM 身份验证的 API 网关端点,没有自定义域名,没有 API 密钥,API 部署到 Prod 并且没有启用 AWS WAF (TBMK) 和VPC代理集成请求方式。

我正在从 Lambda 调用此端点(附加 execute-api:Invoke 调用 API 的权限),但是我收到消息 Forbidden 的 403 错误。 请注意,如果我删除 IAM 身份验证方法,来自 Lambda 的调用将正常工作

我已经看过 this and this SO questions + AWS Doc on the topic 但我已经尝试过这些解决方案(如前所述)。

在 Lambda 中调用 API 网关的示例代码:

final HttpURLConnection connection = (HttpURLConnection) new URL(postApiUrl).openConnection();
connection.setRequestMethod("POST");
final int responseCode = connection.getResponseCode();
//...

我如何将 API 网关 ARN 附加到 CDK 中的 Lambda 角色:

this.addToRolePolicy(
      new PolicyStatement({
          actions: [execute-api:Invoke],
          effect: Effect.ALLOW,
          resources: [postMethod.methodArn],
      }),
);

APIG 有一个授权缓存,检查一下。

https://aws.amazon.com/premiumsupport/knowledge-center/api-gateway-403-error-lambda-authorizer/

如果您可以阅读并详细说明,我会提供适当的解决方案。

您已为您的 API GW 方法设置 IAM 身份验证,但您的 Lambda 函数代码未签署向 API GW 发出的请求。注意:简单地向 Lambda 函数执行角色添加 execute-api:Invoke 权限不会签署请求。

您需要使用 AWS SigV4 签名过程添加身份验证信息,然后在 API GW 端进行验证。 doc 列出了主要涉及的步骤:

  1. Create a canonical request.
  2. Use the canonical request and additional metadata to create a string for signing.
  3. Derive a signing key from your AWS secret access key. Then use the signing key, and the string from the previous step, to create a signature.
  4. Add the resulting signature to the HTTP request in a header or as a query string parameter.

由于您使用的是Java,this blog post也提供了一些示例代码,您可以参考。