How to whitelist IP addresses in Amazon HTTP API

Written by: Chirag (Srce Cde)


How to enable Amazon HTTP API to serve requests originating from specific IP addresses?

In this article, I will share how to whitelist IP addresses within HTTP API to entertain requests originating from whitelisted IP addresses and reject the rest of the requests.

Unlike REST API, HTTP API does not have an option of resource policy where one can add the functionality to control the traffic based on IP addresses. Hence, to add the functionality within HTTP API one of the options is to control the traffic via Lambda Authorizers with Simple or IAM policy response mode.

As a next step, we will create a setup of how to enable Amazon HTTP API to entertain requests based on origin.

Hands-on

We will set up everything from scratch. To get started, create two lambda functions (one for the back-end integration of the specific API route and another for Authorization).


Lambda function 1 (Back-end integration)

After creating the second lambda function, update the source code of the same from here

The above code will check & validate the static authorization token as a part of the IAM policy response mode (can be extended to add/validate other methodologies)along with the validation of request origin.


aws lambda authorizer
Lambda function 2 (Lambda Authorizer)

Post deploying the code, add the environment variable IP_RANGE with the list of IP addresses that need to be whitelisted.


aws lambda authorizer
Environment variable (Lambda)

As a next step, create the HTTP API from API Management Console. Post creation, create the route (/test) along with the GET method.

Next, create and attach the lambda integration (Lambda function 1) to the GET method.

Finally, create and attach the lambda authorization (Lambda function 2) to the GET method.


aws lambda authorizer

While the HTTP API is created, it comes with a default stage and the auto-deployment is enabled. Hence, we can use it.

Here, the setup is successful. Now, we can test it.

Testing

For testing, we will use Postman and the setup will look as below.



The API endpoint will return 403 Forbidden if the IP address is not whitelisted as a part of an IP_RANGE environment variable.


aws lambda authorizer
Result, before whitelisting the IP

After whitelisting the IP address as a part of an IP_RANGE environment variable, the endpoint will return status code 200 with an appropriate response.


aws lambda authorizer
Result, after whitelisting the IP

Finally, we made our endpoint secure in a way.


For a detailed end-to-end, step-by-step setup, you can refer to the video below.



Thank you for reading!