我目前正在编写一个 Node.js lambda 函数,我想在其中记录传入请求者的公共 IP 地址。我整天都在查看 API Gateway 和 Lambda 文档,但没有找到解决方案。
lambdaevent
对象是否包含可用于提取用户 IP 的请求元数据?
我目前正在编写一个 Node.js lambda 函数,我想在其中记录传入请求者的公共 IP 地址。我整天都在查看 API Gateway 和 Lambda 文档,但没有找到解决方案。
lambdaevent
对象是否包含可用于提取用户 IP 的请求元数据?
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 地址。
$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);
};
在 API 网关中,它的价值
$context.identity.sourceIp
您可以通过映射模板将其传递给您的 Lambda。
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)
}
exports.handler = (event, context) => {
console.log('ip:', event.headers["x-forwarded-for"].split(",")[0].trim());
};