AWS - API Gateway - πŸ”’ Only Allow Requests From Your IP

Introduction

 
When we’re first learning how to use the various services offered by AWS, we need to practice using these services. But when we practice, we need to be very mindful about what we’re doing. For instance, if you’re using a free-tier account to practice, you typically want to delete anything you create while practicing once you’re done using it. This can prevent mistakes that could be costly.
 
Let’s say, hypothetically, we created an AWS Lambda function that returns some data. We expose this Lambda function via an API Gateway, and because we’re just learning how to use API Gateway, we may not know anything about security in AWS, or how to actually get an API to work in the first place. So we create our test API--not implementing any security measures--and we start trying to integrate this new API in our project.
 
Eventually it works, then you log off for the night and go to sleep. You wake up the next morning, check your email, and see an alert from AWS saying you’ve used up all of your free-tier for this month. Oops.
 
Someone found that practice API.
 

The Solution

 
Luckily the solution to this is very simple. We can tell our API that we only accept requests from trusted IP addresses. This will cause the API to reject all requests from any IP address that isn’t explicitly provided.
 
First, navigate to the API Gateway service in AWS
 
 
Click on the name of the API you want to secure. In this case it's PetStore (this is one of the example APIs you can create in API Gateway)
 
Next, click on Resource Policy on the navigation bar
 
 
 

The Copy/Paste You Came For 

 
In that box shown above, paste in the following configuration, 
  1. {  
  2.   "Version""2012-10-17",  
  3.   "Statement": [{  
  4.       "Effect""Allow",  
  5.       "Principal""*",  
  6.       "Action""execute-api:Invoke",  
  7.       "Resource""execute-api:/*/*/*"  
  8.     },  
  9.     {  
  10.       "Effect""Deny",  
  11.       "Principal""*",  
  12.       "Action""execute-api:Invoke",  
  13.       "Resource""execute-api:/*/*/*",  
  14.       "Condition": {  
  15.         "NotIpAddress": {  
  16.           "aws:SourceIp""YOUR.IP.HERE"  
  17.         }  
  18.       }  
  19.     }  
  20.   ]  
  21. }   
Make sure to add your own IP address where it says YOUR.IP.HERE
 
You can quickly find your IP address by googling “what is my IP”

Finally, click Save.
 
 

Summary

 
Your API now only allows requests that are made from your IP address. This will prevent any abuse to your free-tier resources and you can even keep your APIs active now that you don’t have to worry about an outside attack using all your resources.
 
Feel free to bookmark this and use it as a quick reference every time you make a public resource in AWS while practicing.
 
Happy learning! Stay safe.


Similar Articles