如何从 AWS API 网关 cloudwatch 日志中获取用户的 public IP?

How to Get User's public IP from AWS API Gateway cloudwatch Logs?

我正在尝试将用户的 public IP 地址记录到 AWS API 网关中的 CloudWatch 日志中。

我创建了一个名为 SourceIP 的模型,并尝试根据 AWS 官方文档添加以下架构,但它给了我错误。

代码:

{
     "source_ip" : "$context.identity.sourceIp"
    
}

错误:

Invalid model specified: Validation Result: warnings : [], errors : [Invalid model schema specified. Unsupported keyword(s): ["source_ip"]]

我的架构可能有什么问题?

如有任何帮助,我们将不胜感激。

谢谢。

Use a mapping template to override an API's request and response parameters and status codes

Mapping template overrides cannot be used with proxy integration endpoints, which lack data mappings

  • 模型仅用于表示输入和输出格式
  • 用于转换数据的映射模板

您可以按照以下步骤启用登录 API 网关:

  1. 创建附加 arn:aws:iam::aws:policy/service-role/AmazonAPIGatewayPushToCloudWatchLogs 权限并遵循信任策略的 IAM
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Sid": "",
      "Effect": "Allow",
      "Principal": {
        "Service": "apigateway.amazonaws.com"
      },
      "Action": "sts:AssumeRole"
    }
  ]
}
  1. 中设置此 IAM 角色
- In the API Gateway console, on the APIs pane, choose the name of an API that you created.
- In the left navigation pane, at the bottom, choose Settings.
- Under Settings, for CloudWatch log role ARN, paste the IAM role ARN that you copied.
- Choose Save.

现在有两种记录IP地址的方法

  • 转到 AWS 控制台中的 AWS API 网关实例。 Select 左侧菜单中的阶段,然后是 select Logs/Tracing 选项卡 Toggle on Enable CloudWatch Logs and select Log Level as INFO

然后

您可以通过

启用映射模板

这导致访问日志如下:

除此之外,您还可以在 Method request headers 中看到 IP 地址

(b1fe0021-8064-4be8-a548-203c6fd795a6) Method request headers: 

{accept-language=en-us, User-Agent=Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_6) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/14.0.3 Safari/605.1.15, 
X-Forwarded-Proto=https, 
X-Forwarded-For=8.xx.xx.xx, 
Host=xxxxx.execute-api.eu-central-1.amazonaws.com, 
X-Forwarded-Port=443, accept-encoding=gzip, deflate, br,
X-Amzn-Trace-Id=Root=1-602e74b0-439e58b379ac537c27664a34, accept=text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8}

如果您不启用 CloudWatch 登录,IP 地址的此信息也将通过映射模板传递到端点。 就像 中描述的那样,例如 lambda。

'use strict';
console.log('Loading function');
exports.handler = (event, context, callback) => {
    console.log('SourceIP =', event.identity.sourceIP);
    callback(null, event.identity.sourceIP);
};

  • 转到 AWS 控制台中的 AWS API 网关实例。 Select 左侧菜单上的阶段,然后 select Logs/Tracing 选项卡启用访问日志记录并添加您要记录的 cloudwatch 日志组。

    • 添加 JSON 日志,我添加了一些和 IP 地址。
{   
    "ip": "$context.identity.sourceIp", 
    "apiId": "$context.apiId",
    "requestId": "$context.requestId", 
    "requestTime": "$context.requestTime", 
    "protocol": "$context.protocol", 
...

...
}
  • 单击“保存更改”即可! API 日志应该会在几分钟后开始显示。

How do I enable CloudWatch Logs for troubleshooting my API Gateway REST API or WebSocket API?