shou2017.com
JP

Setting IP restrictions on ApiGateway with AWS-CDK

Tue Aug 20, 2024
Tue Aug 20, 2024
AWS

When setting IP restrictions on ApiGateway, it’s common to use AWS WAF, but for development or simple restrictions, you can also use ApiGateway’s resource policy to set IP restrictions.

I often use this, so I’m making a note for reference.

Here’s an implementation example with CDK (TypeScript):

// CDK

// Set the allowed IPs
const IP_WHITE_LIST = ["xxx.xxxx",];

new RestApi(this, "Api", {
  restApiName: "api",
  deploy: true,
  cloudWatchRole: true,
  cloudWatchRoleRemovalPolicy: cdk.RemovalPolicy.DESTROY,
  deployOptions: {
    stageName: stage,
    tracingEnabled: true,
    dataTraceEnabled: true,
    loggingLevel: MethodLoggingLevel.INFO,
  },
  policy: new PolicyDocument({
    statements: [
      // IP restriction
      new PolicyStatement({
        effect: Effect.DENY,
        principals: [new AnyPrincipal()],
        actions: ["execute-api:Invoke"],
        resources: ["execute-api:/*/*/*"],
        conditions: {
          NotIpAddress: {
            "aws:SourceIp": IP_WHITE_LIST,
          },
        },
      }),
    ],
  }),
});

In the Conditions block, specify NotIpAddress and set the IP addresses that are allowed access. With just this, IP restrictions are applied. This is effective when you don’t want to use AWS WAF and want to keep costs down.

See Also