This post will demonstrate how to set up an IAM policy for API Gateway that restricts access to the API based on an IP whitelist – meaning only calls to the API will only be allowed if they originate from the IPs defined in the list.
The definition is different depending on the type of API Gateway – we will cover both the REST and Http variants of API Gateway.
Just mentioning that Http APIs should be the default choice for any new API Gateway implementation – they are faster, cheaper and easier to define and work with. But there are situations where REST APIs may have to be used like if a 3rd party callback service only works with basic authentication and not JWT.
Creating an IP Whitelist for an API Gateway REST API
For Rest APIs, this is done in the Auth property of the cloudformation template.yaml
RESTAPI:
Type: AWS::Serverless::Api
Properties:
Name: rest-api
StageName: api
Description: REST API with an IP Whitelist
Auth:
ResourcePolicy:
CustomStatements: [ {
"Effect": "Allow",
"Principal": "*",
"Action": "execute-api:Invoke",
"Resource": "execute-api:/*/*/*"
},
{
"Effect": "Deny",
"Principal": "*",
"Action": "execute-api:Invoke",
"Resource": "execute-api:/*/*/*",
"Condition": {
"NotIpAddress": {
"aws:SourceIp": [
"xx.xxx.xxx.xxx",
"xx.xxx.xxx.x" ]
}
}
}
]
Creating an IP Whitelist for an API Gateway Http API
The definition is much simpler for Http APIs. We can replace the IAM style logic with a simple “IpRangeWhitelist” property.
HttpAPI:
Type: AWS::Serverless::HttpApi
Properties:
Description: REST API with an IP Whitelist
ResourcePolicy:
CustomStatements: [ {
"Effect": "Allow",
"Principal": "*",
"Action": "execute-api:Invoke",
"Resource": "execute-api:/*/*/*"
}]
IpRangeWhitelist:
- "xx.xxx.xxx.xxx"
- "xx.xxx.xxx.x"
Similar definition strategies can be used to create IP block lists.