【问题标题】:How to correctly configure APIGateway for CORS using the CDK如何使用 CDK 为 CORS 正确配置 APIGateway
【发布时间】:2021-10-18 20:00:33
【问题描述】:

我有一个由 AWS ApiGateway 提供的 API,由 AWS Lambda 函数支持并使用 CDK 进行预置。 API 已使用默认 CORS 设置进行配置:

const api = new apiGateway.RestApi(this, "comments-api", {
  defaultCorsPreflightOptions: { allowOrigins: apiGateway.Cors.ALL_ORIGINS }
})

const comments = api.root.addResource("comments")

const comment = comments.addResource("{post_slug}")

comment.addMethod("GET", new apiGateway.LambdaIntegration(listCommentsFunction))

这似乎只为我的 API 提供了部分 CORS 配置。

  • 它使用适当的 CORS 相关标头提供对 OPTIONS 请求的响应,但
  • 似乎它没有使用适当的 CORS 标头对对 GET <api>/comments/{post_slug} 的请求的响应进行水合

这使得 CDK 构造中的 CORS 配置选项不是特别有用 - 因为我似乎更明智地忽略该设置,而是手动配置一个 OPTIONS来自我的 Lambda 的响应,将其更改为:

const api = new apiGateway.RestApi(this, "comments-api")

const comments = api.root.addResource("comments")
const comment = comments.addResource("{post_slug}")

comment.addMethod("GET", new apiGateway.LambdaIntegration(listCommentsFunction))
comment.addMethod("OPTIONS", new apiGateway.LambdaIntegration(listCommentsFunction))

然后确保我的 lambda 始终以正确的标头响应。如果我这样做,那么我将使用 两种 不同的机制使用 CORS 标头来补充我的响应; CDK 堆栈配置和显式处理程序逻辑。这感觉像是一种气味。

出于这个原因,我想知道我是否配置错误,并且有一种方法可以使用 CDK 来配置响应以正确补水。

【问题讨论】:

    标签: typescript amazon-web-services amazon-cloudformation aws-api-gateway aws-cdk


    【解决方案1】:

    CDK 为 OPTIONS 方法生成的代码正在使用响应覆盖 - https://docs.aws.amazon.com/apigateway/latest/developerguide/apigateway-override-request-response-parameters.html

    此选项在您用于 GET 方法的 lambda 代理集成中不可用。除了在 lambda 源代码级别计算 CORS 标头之外,我确实没有找到任何其他选择。

    P.S.:我写了https://milangatyas.com/Blog/Detail/14/setup-cors-for-amazon-api-gateway-via-aws-cdk,在那里你可以得到更详细的信息。

    【讨论】:

      猜你喜欢
      • 2019-12-09
      • 2018-09-13
      • 1970-01-01
      • 2021-10-31
      • 1970-01-01
      • 2020-12-17
      • 2022-01-15
      • 2020-09-21
      • 2012-09-03
      相关资源
      最近更新 更多