如何在 API Gateway Lambda 代理集成中获取 HTTP 标头“Content-Length”

Ste*_*ula 4 amazon-web-services aws-lambda aws-api-gateway

我需要构建一个函数,该函数采用 5 个特定的 HTTP 标头 + 请求参数,对它们进行聚合、排序、编码,然后对它们进行哈希处理,以便验证/验证整个请求。但是,我无法将标头“Content-Length”传递给 lambda。

我使用 Terraform 创建 API 网关 (aws_api_gateway_domain_name),然后使用 Serverless 创建端点:

functions:
  alerts:
    handler: src/event.handler
    role: arn:aws:iam::${env:AWS_ACCOUNT_ID}:role/alerts_lambda
    environment:
      API_TRANS_KEY: ${env:API_TRANS_KEY}
      REGION: ${self:custom.region}
      SNS_ARN: arn:aws:sns:us-east-1:${env:AWS_ACCOUNT_ID}:Transactions
      STAGE: ${self:custom.deploymentStage}
    events:
      - http:
          path: /alerts/AccountEvent
          method: post
          cors: true
          integration: lambda-proxy
Run Code Online (Sandbox Code Playgroud)

但是我得到的标题是:

    "headers": {
        "Accept": "*/*",
        "accept-encoding": "gzip, deflate",
        "Cache-Control": "no-cache",
        "CloudFront-Forwarded-Proto": "https",
        "CloudFront-Is-Desktop-Viewer": "true",
        "CloudFront-Is-Mobile-Viewer": "false",
        "CloudFront-Is-SmartTV-Viewer": "false",
        "CloudFront-Is-Tablet-Viewer": "false",
        "CloudFront-Viewer-Country": "US",
        "Content-Type": "application/x-www-form-urlencoded",
        "Date": "20170504:141752UTC",
        "Encryption-Type": "HMAC-SHA256",
        "Host": "events.dev.myapi.com",
        "Postman-Token": "84bd0cc3-f339-4b2a-8017-31ec9174c37e",
        "User-Agent": "PostmanRuntime/7.11.0",
        "User-ID": "galileo",
        "Via": "1.1 50c3c79d5d7adbc8948ea11709b61d17.cloudfront.net (CloudFront)",
        "X-Amz-Cf-Id": "1OE1aGP_3Q-CkXFuJbRwvkGAR2ZaHAPuozckZ6747EP64zZcmXjphw==",
        "X-Amzn-Trace-Id": "Root=1-5d0bf01b-8afdb9628f42a9357dbb5c68",
        "X-Forwarded-For": "73.72.58.46, 70.132.57.87",
        "X-Forwarded-Port": "443",
        "X-Forwarded-Proto": "https"
    },
Run Code Online (Sandbox Code Playgroud)

此时我需要使用映射模板吗?CloudFront/Api Gateway 是否出于某种原因剥离此标头(请注意,我没有设置 CloudFront 发行版,但 API Gateway 因“边缘”类型​​而正在创建一个发行版,但如果可以解决问题,我可以将其更改为“区域”)这)?

Par*_*igm 5

根据我的测试,Content-Length在发出 API 请求时,标头可以通过。但是,它不会出现在 Lambda 代理集成的事件负载中。

您可以使用两种替代方法来接收Content-Length标头:

  • 在 API Gateway 中使用带有 Lambda 代理集成的HTTP API,而不是 REST API。

  • 使用REST API 的Lambda 非代理集成并按如下方式配置:

    1. 在集成请求的映射模板中:

      • 设置application/jsonContent-Type
      • 通过添加语句来更改默认的“方法传递模板”模板 -"X-Content-Length" : $input.body.length()
    2. 在 Lambda 函数中,变量 event['X-Content-Length']将包含Content-Length.