1
votes

I am using AWS API Gateway as a http proxy to my rest api application. The thing is, I can't seem to find a way to get the client ip address or to pass it through to my application from the api gateway. The only way I saw was to use a lambda function, but I can't use it because it have to be a http integration.

Is there any other way to do that?

4

4 Answers

1
votes

Just configure request payload-mapping. What you need is $context.identity.sourceIp. According to documentation:

$context.identity.sourceIp

The source IP address of the TCP connection making the request to API Gateway.

Documentation with examples is available at http://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-mapping-template-reference.html

1
votes

You can do this in the mapping template of your integration response. Call $context.identity.sourceIp to get the sourceIp.

If you're already using a mapping template, then you can just add this at any convenient point. If you aren't currently using a mapping template and just need to add the sourceIp to an incoming json request body, add a mapping template like so:

#set($allParams = $input.path('$'))
#set($discard=$allParams.put('sourceIp', $context.identity.sourceIp))
$input.json('$'))
0
votes

If you are using "proxy"-style integration, the client IP is available inside the request (no template mapping is required). Follow the code example from the link above and dig inside "event" JSON object:

requestContext -> identity -> sourceIp
0
votes

If you are working with API Gateway's HTTP APIs (announced in Dec 2019), be aware of the payload format version under Advanced Settings in Integrations. You can pick between 1.0 and 2.0.

Using Kotlin code as examples, for 1.0, you can retrieve the source IP from APIGatewayProxyRequestEvent as follows.

event.requestContext.identity.sourceIp

For 2.0, you can retrieve the source IP from APIGatewayV2HTTPEvent as follows.

event.requestContext.http.sourceIp