Whitelist IP Addresses in Serverless Frameworks

Protect your API from bad actors by restricting it to the IP addresses you trust

Feb 1 · 3 min read
Photo by Chepe Nicoli on Unsplash


One way to protect our APIs is via IP address restriction. This is where we specify the range of IP addresses that are allowed to call our API endpoints. Fortunately, AWS API Gateway supports this protection mechanism, known as resource policies.

When developing APIs via the serverless framework, we can specify our API Gateway configuration in the serverless.yml. Fundamentally, what can be written in the CloudFormation template can also be written in serverless.yml.

What You Will Learn

Configure the Resource Policy to Whitelist IP Addresses

Let’s see how to write the resource policy that restricts which IP addresses can invoke our APIs hosted on API Gateway.


Let’s go through a few key points here.



It is possible to only restrict access to particular endpoint(s). In this case, the value we put for the Resource field would be something like this:


This will apply the resource policy only to our /authentication endpoint. So, if there are other API endpoints hosted on the same API Gateway, they will not be restricted.


- ""
- ""

This indicates that only those source IP addresses are allowed to do the execute-api:Invoke action.

If you try to call the API from any IP address other than those two, you will get an error like this:

{"Message": "User: anonymous is not authorized to perform: execute-api: Invoke on resource: arn:aws:execute-api:ap-southeast-1:123456789012:qwa2y1c3m4/dev/POST/authentication"}

That’s it! Well done, guys!

It was pretty simple and straightforward, right?

Other Ways to Secure Your APIs

  • Configure the usage plan on API Gateway. The usage plan allows you to set how many requests per second and how many total requests over a certain period of time (e.g. per day, per week, or per month) are allowed.
  • Put input validation in the class object that deserializes the request body. You can see how to do that in Python here: Protect your API via Input Validation in Python 3 Data Class.

Wrap Up

As mentioned previously, there are other ways to protect your APIs. I encourage you to explore other options and choose the one that fits your needs the most.

That’s it! Till next time.

Better Programming

Advice for programmers.


Written by

A passionate Software Engineer trying to leave a good legacy on earth

Better Programming

Advice for programmers.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade