如何通过 Amazon API 网关 + Lambda(节点)检索用户的 public IP 地址

How can I retrieve a user's public IP address via Amazon API Gateway + Lambda (node)

我目前正在编写一个 Node.js lambda 函数,我想在其中记录传入请求者的 public IP 地址。我一整天都在查看 API Gateway 和 Lambda 文档,但没有找到解决方案。

lambda event 对象是否包含我可以用来提取用户 IP 的请求元数据?

在API网关中,它是值

$context.identity.sourceIp

http://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-mapping-template-reference.html#context-variable-reference

您可以通过映射模板将其传递给您的 Lambda。

这是在 Lambda 函数中使用 API 网关的 $context.identity.sourceIp 的简单演示。

API 映射模板:

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

Lambda 函数:

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

HTTP 更新 APIs

添加@Elijah 的评论。 HTTP API 的格式将为

event['requestContext']['http']['sourceIp']

编辑

更好的方法实际上是检查

event['requestContext']['identity']['sourceIp']

您还可以从相同的 object

中获取 User-Agent
event['requestContext']['identity']['userAgent']

请参阅下面 Cesar 的评论。 Headers 很容易被欺骗,用户可以将 X-Forwarded-For 设置为任何值。据我所知,上面的 sourceIp 是从 TCP 连接中检索到的。

原回答

自 2017 年 9 月起,您可以在 API 网关中创建一个方法与 Lambda 代理集成,这将使您能够访问

events['headers']['X-Forwarded-For']

看起来像 1.1.1.1,214.25.52.1

第一个ip1.1.1.1是你用户的publicip地址。

exports.handler = (event, context) => {
    console.log('ip:', event.headers["x-forwarded-for"].split(",")[0].trim());
};

API 网关应该已经在 http header X-Forwarded-For 中包含远程 IP,因此您可以:

// Lambda handler function
module.exports.handlerFunc = async (event, context) => {
    // `X-Forwarded-For` should return a comma-delimited list of IPs, first one being remote IP:
    // X-Forwarded-For: '<remote IP>, <cloudfront/API gateway IP>, ...'
    const remoteIp = event.headers['X-Forwarded-For'].split(', ')[0]
    // If you want to see more info available in event and context, add following, deploy and check CloudWatch log:
    // console.log(event, context)
}