6
5

More than 1 year has passed since last update.

API Gatewayで特定のリソースのみ、IP制限する方法

Last updated at Posted at 2021-12-30

はじめに

メンテナンス性も考慮した、API Gatewayの一部のリソースのみIP制限する方法についてまとめました。

前提条件

例として、hoge1,hoge2,fuga1,fuga2の4つのリソースを作成するとします。
作成する際、IP制限ありhoge1,hoge2の手前にrestrictionをつけます。
対して、IP制限なしfuga1,fuga2の手前にはfreeをつけます。

実際にIP制限する際に楽になりますので、説明した通りに作成しましょう。

スクリーンショット 2021-12-30 16.42.51.png

4つのURL

IP制限あり

  • https://~/prod/restriction/hoge1
  • https://~/prod/restriction/hoge2

IP制限なし

  • https://~/prod/restriction/fuga1
  • https://~/prod/restriction/fuga2

リソースポリシーで、一部のみIP制限する

左のリソースポリシーをクリックしましょう。

スクリーンショット 2021-12-30 16.49.59.png

以下をコピペします。
ステージは、prodとします。
<account-id>は、文字通りAWSアカウントIDです。
<api-id>は、apigatewayのIDになります。(下記画像の赤線箇所です。)

スクリーンショット 2021-12-30 16.53.16.png

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Principal": "*",
      "Action": "execute-api:Invoke",
      "Resource": "arn:aws:execute-api:ap-northeast-1:<account-id>:<api-id>/prod/*/*/*"
    },
    {
      "Effect": "Deny",
      "Principal": "*",
      "Action": "execute-api:Invoke",
      "Resource": "arn:aws:execute-api:ap-northeast-1:<account-id>:<api-id>/prod/*/restriction/*",
      "Condition": {
        "NotIpAddress": {
          "aws:SourceIp": ["111.111.11.11/32", "222.222.22.22/32"]
        }
      }
    }
  ]
}

リソースポリシーの解説

上のAllowでは、全てのapiを許可しています。

下のDenyでは、/prod/*/restriction/*としており、restriction配下のリソースであるhoge1hoge2のみIP制限できます。

手前にrestrictionをつけることで、
今後、IP制限したいリソースやIP制限しなくないリソースが出た際に、
リソースポリシーを修正する必要はなく、メンテが楽なため、
最初に、restriction
freeをつけるとよいと思います。

ちなみに、restriction配下のGETメソッドのみIP制限したい場合、以下のようにGETをつけるとよいです。

/prod/GET/restriction/

その他、リソースポリシーの一般的なユースケースはこちらが参考になります。

すべてのリソースをIP制限する場合

ちなみにすべてのリソースをIP制限する場合は、以下のとおりです。

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Principal": "*",
      "Action": "execute-api:Invoke",
      "Resource": "arn:aws:execute-api:ap-northeast-1:<account-id>:<api-id>/prod/*/*/*"
    },
    {
      "Effect": "Deny",
      "Principal": "*",
      "Action": "execute-api:Invoke",
      "Resource": "arn:aws:execute-api:ap-northeast-1:<account-id>:<api-id>/prod/*/*/*",
      "Condition": {
        "NotIpAddress": {
          "aws:SourceIp": ["111.111.11.11/32", "222.222.22.22/32"]
        }
      }
    }
  ]
}
6
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
5