63

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

lambdaevent对象是否包含可用于提取用户 IP 的请求元数据?

4

5 回答 5

64

HTTP API 更新

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

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

编辑

更好的方法实际上是检查

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

您还可以从同一对象获取用户代理

event['requestContext']['identity']['userAgent']

请参阅下面的 Cesar 评论。标题很容易被欺骗,用户可以设置X-Forwarded-For任何东西。AFAIKsourceIp以上是从 TCP 连接中检索到的。

原始答案

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

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

看起来像1.1.1.1,214.25.52.1

第一个 ip1.1.1.1是您用户的公共 IP 地址。

于 2017-09-03T08:45:35.040 回答
51

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

API 映射模板:

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

拉姆达函数:

'use strict';
console.log('Loading function');
exports.handler = (event, context, callback) => {
    console.log('SourceIP =', event.identity.sourceIP);
    callback(null, event.identity.sourceIP);
};
于 2016-06-01T05:44:48.087 回答
17

在 API 网关中,它的价值

$context.identity.sourceIp

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

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

于 2015-10-11T21:06:37.327 回答
2

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

// 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)
}
于 2020-08-09T20:51:34.867 回答
-2
exports.handler = (event, context) => {
    console.log('ip:', event.headers["x-forwarded-for"].split(",")[0].trim());
};
于 2020-06-15T08:34:11.713 回答