Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I'm currently writing a Node.js lambda function, in which I want to log the incoming requester's public IP address. I've been looking through both the API Gateway and Lambda docs all day, but haven't found a solution.

Does the lambda event object include request metadata I can use to extract the user's IP?

like image 532
rdegges Avatar asked Oct 11 '15 06:10

rdegges


People also ask

Can Lambda have public IP?

This function simply prints the public IP used by lambda(which is our NAT instance IP) and then stops our NAT instance. That's all for setup. Once the trigger lambda is executed, check the logs for ip lambda to make sure the setup is working fine.

Does AWS API gateway have an IP?

Your API gateway is now accessible via static IP addresses provided by AWS Global Accelerator.


1 Answers

Update for HTTP APIs

Adding @Elijah's comment. The format for HTTP APIs will be

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

Edit

A better way is actually to check

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

You can also get the User-Agent from the same object

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

See Cesar's comment below. Headers are easily spoofed and the user can set X-Forwarded-For to anything. AFAIK the sourceIp above is retrieved from the TCP connection.

Original answer

As of September 2017, you can create a method in API Gateway with Lambda Proxy integration, this will give you access to

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

Which will look something like 1.1.1.1,214.25.52.1

The first ip 1.1.1.1 is your user's public ip address.

like image 118
Jonathan Avatar answered Oct 23 '22 11:10

Jonathan