首页 > 解决方案 > 在 Lambda 中获取用户的 IP 地址(使用 API Gateway 和 Python)

问题描述

我正在使用这种技术(如何使用 Python 检索 AWS Lambda 公共 IP 地址?),但它提供了 AWS 内 Lambda 服务器的 IPAddress。

基于此:How can I retrieve a user's public IP address via Amazon API Gateway + Lambda (node),看起来我应该可以使用

ip_address = event['requestContext']['identity']['sourceIp'];

我的处理程序是这样开始的:

def lambda_handler(event, context):

但如果我做 a pprint.pprint(event),我看不到任何 RequestContext ,只有“正文”。

FFXSam 对 Jonathan 回答的最后一条评论说:“应该注意,如果您提供的页面不在授权者后面,则 event.requestContext.identity 不存在。”。我不确定这意味着什么或为什么它是真的。我正在使用 API Gateway,客户端的 JavaScript 代码正在调用它。

我可以要求客户端编码器向我发送正文中的本地 IP 地址,但似乎我应该能够在 Lambda 函数本身中获取它。

有人询问事件,尽管我说它只有在名为“body”的 json 元素中传递的字段:

代码:

print("pprint event:")
pprint.pprint(event)


2021-06-06T13:30:01.231-05:00   pprint event:
2021-06-06T13:30:01.231-05:00   {'body': {'ResponseTimeMilliseconds': 2225,
2021-06-06T13:30:01.231-05:00   'authToken': '12312312',
2021-06-06T13:30:01.231-05:00   'handNumber': 7}}

标签: amazon-web-servicesaws-lambdapython-3.7

解决方案


我将赏金奖励给了 Muzaffar Shaikh,但在这里我将给出更彻底的解释,这似乎是 StackOverflow 所缺乏的。他的回答得到了 IP 地址,但删除了我的“body”字段,但它确实为我指明了正确的方向。

在 AWS API Gateway 工具中,单击“资源”,然后单击您的方法(我的是“发布”),然后单击“集成请求”,如此处所示。 在此处输入图像描述

向下滚动到底部,如果没有任何模板,请输入“application/json”并单击复选框(注意,“application/json”以浅灰色字母显示,但只需单击复选框而不键入它就不会'不工作)。

在此处输入图像描述 然后我输入以下模板:

{
   "client_ip" : "$input.params('X-Forwarded-For')",
   "user_agent" : "$input.params('User-Agent')",
   "body" : $input.json('$.body') 
}

注意:如果我输入 $input.json('$') 或 $input.json('body'),我最终会在我的“body”字段中添加一个“body”字段,这破坏了当前的逻辑。

网页完成后,它看起来像这样:

在此处输入图像描述

下一步是将模板重新部署到您正在使用的“部署阶段”(环境)。

在此处输入图像描述

在此处输入图像描述

顺便说一下,在输入模板的时候,如果你在“生成模板”下拉框中点击“方法请求直通”,它会生成一个这样的模板(我没有使用这个选项,但是很快就会阅读更多关于它的内容) ):

##  See http://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-mapping-template-reference.html
##  This template will pass through all parameters including path, querystring, header, stage variables, and context through to the integration endpoint via the body/payload
#set($allParams = $input.params())
{
"body-json" : $input.json('$'),
"params" : {
#foreach($type in $allParams.keySet())
    #set($params = $allParams.get($type))
"$type" : {
    #foreach($paramName in $params.keySet())
    "$paramName" : "$util.escapeJavaScript($params.get($paramName))"
        #if($foreach.hasNext),#end
    #end
}
    #if($foreach.hasNext),#end
#end
},
"stage-variables" : {
#foreach($key in $stageVariables.keySet())
"$key" : "$util.escapeJavaScript($stageVariables.get($key))"
    #if($foreach.hasNext),#end
#end
},
"context" : {
    "account-id" : "$context.identity.accountId",
    "api-id" : "$context.apiId",
    "api-key" : "$context.identity.apiKey",
    "authorizer-principal-id" : "$context.authorizer.principalId",
    "caller" : "$context.identity.caller",
    "cognito-authentication-provider" : "$context.identity.cognitoAuthenticationProvider",
    "cognito-authentication-type" : "$context.identity.cognitoAuthenticationType",
    "cognito-identity-id" : "$context.identity.cognitoIdentityId",
    "cognito-identity-pool-id" : "$context.identity.cognitoIdentityPoolId",
    "http-method" : "$context.httpMethod",
    "stage" : "$context.stage",
    "source-ip" : "$context.identity.sourceIp",
    "user" : "$context.identity.user",
    "user-agent" : "$context.identity.userAgent",
    "user-arn" : "$context.identity.userArn",
    "request-id" : "$context.requestId",
    "resource-id" : "$context.resourceId",
    "resource-path" : "$context.resourcePath"
    }
}

映射模板的两个参考:

  1. https://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-mapping-template-reference.html
  2. https://docs.aws.amazon.com/apigateway/latest/developerguide/models-mappings.html

关于何时使用“$input.params”与“$context.some_value”,我还有一些研究要做。


推荐阅读