Reputation: 5177
I am trying to get the user's ip address in a lambda function called from AWS AppSync.
I tried with this input resolver:
{
"version" : "2017-02-28",
"operation": "Invoke",
"payload": {
"arguments": $util.toJson($context.arguments),
"sourceIp" : $context.identity.sourceIp
}
}
But I found while testing that $context.identity
is null when I call the function through the AppSync queries dashboard.
Are there other ways to get the user's ip address or am I doing something wrong?
Thank you.
Update: With the help of aldarisbm, I came up with this input resolver:
#set ($forwardHeader = "${context.request.headers.X-Forwarded-For}")
#set ($comma = $forwardHeader.indexOf(','))
#set ($ip = $forwardHeader.substring(0, $comma))
#set ($payload = $context.arguments)
#set ($discard = $payload.put("sourceIp", "${ip}"))
{ "version" : "2017-02-28", "operation": "Invoke", "payload": $util.toJson($payload) }
Upvotes: 1
Views: 1353
Reputation: 407
I haven't used $context.identity
specifically but have you tried checking the headers that AWS adds to your requests:
https://docs.aws.amazon.com/elasticloadbalancing/latest/classic/x-forwarded-headers.html
There's a X-Forwarded-For: client-ip-address
, header that gets added to requests.
This should solve your problem.
Upvotes: 1