【问题标题】:How to Get User's public IP from AWS API Gateway cloudwatch Logs?如何从 AWS API Gateway cloudwatch 日志中获取用户的公共 IP?
【发布时间】:2021-05-21 08:21:12
【问题描述】:

我正在尝试将用户的公共 IP 地址记录到 AWS API Gateway 中的 CloudWatch 日志中。

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

代码:

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

错误:

指定的模型无效:验证结果:警告:[],错误: [指定的模型架构无效。不支持的关键字: ["source_ip"]]

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

任何帮助将不胜感激。

谢谢。

【问题讨论】:

标签: json amazon-web-services aws-api-gateway amazon-api-gateway


【解决方案1】:

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

映射模板覆盖不能与缺少数据映射的代理集成端点一起使用

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

您可以按照以下步骤启用登录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 Gateway 实例。在左侧菜单中选择 Stages,然后选择 Logs/Tracing 选项卡 Toggle on Enable CloudWatch Logs 并选择 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 地址的信息也将通过映射模板传递到端点。 就像this answer 中描述的一样,例如 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 Gateway 实例。在左侧菜单中选择 Stages,然后选择 Logs/Tracing 选项卡切换到 Enable Access Logging 并将您的 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?

【讨论】:

    猜你喜欢
    • 2017-10-10
    • 2020-05-27
    • 2020-10-25
    • 2019-02-19
    • 1970-01-01
    • 1970-01-01
    • 2019-07-09
    • 1970-01-01
    • 2018-01-07
    相关资源
    最近更新 更多