gcloud CLI を使用してサービスへのトラフィックを保護する

このページでは、API Gateway に API をデプロイして、バックエンド サービスへのトラフィックを保護する方法について説明します。

Google Cloud CLI を使用して Cloud Functions でバックエンド サービスにアクセスする新しい API をデプロイするには、次の手順に沿って操作します。このクイックスタートでは、API キーを使用してバックエンドを不正アクセスから保護する方法についても説明します。

準備

  1. Google Cloud コンソールで [ダッシュボード] ページに移動し、Google Cloud プロジェクトを選択または作成します。

    [ダッシュボード] ページに移動する

  2. お支払いが有効になっていることを確認します。

    課金を有効にする方法について

  3. Google Cloud CLI がマシンにダウンロードされ、インストールされていることを確認します。

    gcloud CLI をダウンロードする

  4. gcloud コンポーネントを更新します。

    gcloud components update
  5. デフォルト プロジェクトを設定します。PROJECT_ID は、Google Cloud プロジェクト ID に置き換えます。

    gcloud config set project PROJECT_ID

必要なサービスを有効にする

API Gateway では、次の Google サービスを有効にする必要があります。

名前 タイトル
apigateway.googleapis.com API Gateway API
servicemanagement.googleapis.com Service Management API
servicecontrol.googleapis.com Service Control API

必要なサービスが有効になっていることを確認するには:

gcloud services list

必要なサービスが表示されない場合は、次のコマンドを使用してサービスを有効にします。

gcloud services enable apigateway.googleapis.com
gcloud services enable servicemanagement.googleapis.com
gcloud services enable servicecontrol.googleapis.com

gcloud サービスの詳細については、gcloud サービスをご覧ください。

API バックエンドをデプロイする

API Gateway は、デプロイされたバックエンド サービスの前にあり、すべての受信リクエストを処理します。このクイックスタートでは、API Gateway は、以下に示す関数を含む helloGET という名前の Cloud Functions バックエンドに受信呼び出しをルーティングします。

/**
 * HTTP Cloud Function.
 * This function is exported by index.js, and is executed when
 * you make an HTTP request to the deployed function's endpoint.
 *
 * @param {Object} req Cloud Function request context.
 *                     More info: https://expressjs.com/en/api.html#req
 * @param {Object} res Cloud Function response context.
 *                     More info: https://expressjs.com/en/api.html#res
 */

exports.helloGET = (req, res) => {
  res.send('Hello World!');
};

クイックスタート: Google Cloud CLI の使用の手順に沿ってサンプル Cloud Functions コードをダウンロードし、Cloud Functions 関数のバックエンド サービスをデプロイします。

API の作成

これで、API Gateway で API を作成する準備が整いました。

  1. 次のコマンドを入力します。ここで、

    • API_ID は API の名前を指定します。 API の命名ガイドラインについては、API ID の要件をご覧ください。
    • PROJECT_ID は Google Cloud プロジェクトの名前を指定します。
    gcloud api-gateway apis create API_ID --project=PROJECT_ID

    次に例を示します。

    gcloud api-gateway apis create my-api --project=my-project
  2. 正常に完了すると、次のコマンドを使用して新しい API の詳細を表示できます。

    gcloud api-gateway apis describe API_ID --project=PROJECT_ID

    次に例を示します。

    gcloud api-gateway apis describe my-api --project=my-project

    このコマンドを実行すると、次のようなフィード レスポンスが返されます。

      createTime: '2020-02-29T21:52:20.297426875Z'
      displayName: my-api
      managedService: my-api-123abc456def1.apigateway.my-project.cloud.goog
      name: projects/my-project/locations/global/apis/my-api
      state: ACTIVE
      updateTime: '2020-02-29T21:52:20.647923711Z'

managedService プロパティの値をメモします。この値は、次のステップで API を有効にするために使用します。

API 構成の作成

API Gateway を使用して、デプロイされた API バックエンドへのトラフィックを管理するには、API 構成が必要です。

特殊なアノテーションを含む OpenAPI 仕様を使用して API 構成を作成し、必要な API Gateway の動作を定義できます。このクイックスタートで使用する OpenAPI 仕様には、Cloud Functions のバックエンドへのルーティング手順が含まれています。

# openapi2-functions.yaml
swagger: '2.0'
info:
  title: API_ID optional-string
  description: Sample API on API Gateway with a Google Cloud Functions backend
  version: 1.0.0
schemes:
  - https
produces:
  - application/json
paths:
  /hello:
    get:
      summary: Greet a user
      operationId: hello
      x-google-backend:
        address: https://GCP_REGION-PROJECT_ID.cloudfunctions.net/helloGET
      responses:
        '200':
          description: A successful response
          schema:
            type: string

gcloud CLI を使用して、この OpenAPI 仕様をアップロードし、API 構成を作成するには:

  1. コマンドラインから、openapi2-functions.yaml という名前の新しいファイルを作成します。

  2. 新しく作成したファイルに OpenAPI 仕様の内容をコピーして貼り付けます。

  3. ファイルを次のように編集します。

    1. title フィールドで、API_ID を API の名前に置き換え、optional-string を任意の簡単な説明に置き換えます。このフィールドの値は、この API へのアクセス権を付与する API キーを作成するときに使用されます。
    2. address フィールドで、GCP_REGION をデプロイした関数の GCP リージョンに置き換え、PROJECT_ID を Google Cloud プロジェクトの名前に置き換えます。
  4. 次のコマンドを入力します。ここで、

    • CONFIG_ID は API 構成の名前を指定します。
    • API_ID は API の名前を指定します。
    • API_DEFINITION は、OpenAPI 仕様のファイル名を指定します。
    • PROJECT_ID は Google Cloud プロジェクトの名前を指定します。
    • SERVICE_ACCOUNT_EMAIL には、認証が構成されたバックエンドのトークンに署名するために使用されるサービス アカウントを指定します。詳細については、サービス アカウントの構成をご覧ください。
    gcloud api-gateway api-configs create CONFIG_ID \
      --api=API_ID --openapi-spec=API_DEFINITION \
      --project=PROJECT_ID --backend-auth-service-account=SERVICE_ACCOUNT_EMAIL

    次に例を示します。

    gcloud api-gateway api-configs create my-config \
      --api=my-api --openapi-spec=openapi2-functions.yaml \
      --project=my-project --backend-auth-service-account=0000000000000-compute@developer.gserviceaccount.com

    API 構成がダウンストリームのシステムに伝播される際に、このオペレーションが完了するまでに数分を要する場合があります。複雑な API 構成の作成が正常に完了するまでに最大 10 分を要する場合があります。

  5. API 構成が作成されたら、次のコマンドを実行して詳細を表示できます。

    gcloud api-gateway api-configs describe CONFIG_ID \
      --api=API_ID --project=PROJECT_ID

    次に例を示します。

    gcloud api-gateway api-configs describe my-config \
      --api=my-api --project=my-project

    出力では次の例のように API 構成の詳細(名前や状態など)を示します。

    createTime: '2020-02-07T18:17:01.839180746Z'
    displayName: my-config
    gatewayConfig:
    backendConfig:
      googleServiceAccount: 0000000000000-compute@developer.gserviceaccount.com
    name: projects/my-project/locations/global/apis/my-api/configs/my-config
    serviceRollout:
    rolloutId: 2020-02-07r0
    state: ACTIVE
    updateTime: '2020-02-07T18:17:02.173778118Z'

ゲートウェイを作成する

次に、API 構成をゲートウェイにデプロイします。 ゲートウェイに API 構成をデプロイすると、API クライアントで API へのアクセスに使用できる外部 URL が定義されます。

次のコマンドを実行して、作成した API 構成を API Gateway にデプロイします。

gcloud api-gateway gateways create GATEWAY_ID \
  --api=API_ID --api-config=CONFIG_ID \
  --location=GCP_REGION --project=PROJECT_ID

ここで

  • GATEWAY_ID はゲートウェイの名前を指定します。
  • API_ID は、このゲートウェイに関連付けられた API Gateway API の名前を指定します。
  • CONFIG_ID は、ゲートウェイにデプロイされた API 構成の名前を指定します。
  • GCP_REGION は、デプロイされたゲートウェイの Google Cloud リージョンです。

  • PROJECT_ID は Google Cloud プロジェクトの名前を指定します。

次に例を示します。

gcloud api-gateway gateways create my-gateway \
  --api=my-api --api-config=my-config \
  --location=us-central1 --project=my-project

正常に完了したら、次のコマンドを使用してゲートウェイの詳細を表示します。

gcloud api-gateway gateways describe GATEWAY_ID \
  --location=GCP_REGION --project=PROJECT_ID

次に例を示します。

gcloud api-gateway gateways describe my-gateway \
  --location=us-central1 --project=my-project

このコマンドを実行すると、次のようなフィード レスポンスが返されます。

apiConfig: projects/my-project/locations/global/apis/my-api/configs/my-config
createTime: '2020-02-05T13:44:12.997862831Z'
defaultHostname: my-gateway-a12bcd345e67f89g0h.uc.gateway.dev
displayName: my-gateway
name: projects/my-project/locations/us-central1/gateways/my-gateway
serviceAccount:
      email: 0000000000000-compute@developer.gserviceaccount.com
state: ACTIVE
updateTime: '2020-02-05T13:45:00.844705087Z'

defaultHostname プロパティの値をメモします。これは、次のステップでデプロイをテストするために使用するゲートウェイ URL のホスト名の部分です。

API デプロイのテスト

これでゲートウェイのデプロイ時に生成された URL を使用して API にリクエストを送信できるようになりました。

次の curl コマンドを入力します。ここで、

  • DEFAULT_HOSTNAME は、デプロイするゲートウェイ URL のホスト名の部分を指定します。
  • hello は、API 構成で指定されたパスです。
curl https://DEFAULT_HOSTNAME/hello

次に例を示します。

curl https://my-gateway-a12bcd345e67f89g0h.uc.gateway.dev/hello

次のように出力されます。

Hello World!

API Gateway が正常に作成されてデプロイされました。

API キーを使用してアクセスを保護する

API バックエンドへのアクセスを保護するには、プロジェクトに関連付けられた API キーを生成し、そのキーに API を呼び出す権限を付与します。詳しくは、API キーで API アクセスを制限するをご覧ください。

このクイックスタートで使用している Google Cloud プロジェクトに関連付けられた API キーがまだ存在しない場合は、API キーの作成の手順に沿って追加できます。

API キーを使用してゲートウェイへのアクセスを保護するには:

  1. サービスの API キーサポートを有効にします。次のコマンドを入力します。ここで、
    • MANAGED_SERVICE_NAME は、API のデプロイ時に作成されたマネージド サービスの名前を指定します。これは、gcloud apigee-gateway apis describe コマンドで表示されるマネージド サービスのプロパティで確認できます。
    • PROJECT_ID は Google Cloud プロジェクトの名前を指定します。
    gcloud services enable MANAGED_SERVICE_NAME.apigateway.PROJECT_ID.cloud.goog
    例:
    gcloud services enable my-api-123abc456def1.apigateway.my-project.cloud.goog
  2. API 構成の作成に使用される OpenAPI 仕様を変更して、すべてのトラフィックに API キー検証セキュリティ ポリシーを適用する手順を含めます。以下に示すように、security タイプと securityDefinitions を追加します。
      # openapi2-functions.yaml
      swagger: '2.0'
      info:
        title: API_ID optional-string
        description: Sample API on API Gateway with a Google Cloud Functions backend
        version: 1.0.0
      schemes:
        - https
      produces:
        - application/json
      paths:
        /hello:
          get:
            summary: Greet a user
            operationId: hello
            x-google-backend:
              address: https://GCP_REGION-PROJECT_ID.cloudfunctions.net/helloGET
            security:
            - api_key: []
            responses:
              '200':
                description: A successful response
                schema:
                  type: string
      securityDefinitions:
        # This section configures basic authentication with an API key.
        api_key:
          type: "apiKey"
          name: "key"
          in: "query"
    securityDefinition は、仕様で定義されているすべてのパスへのアクセスをリクエストするときに、key という名前のクエリ パラメータとして渡される API キーをリクエストするように API を構成します。
  3. 次のコマンドを使用して、変更した OpenAPI 仕様で新しい API 構成を作成します。
    gcloud api-gateway api-configs create NEW_CONFIG_ID \
    --api=API_ID --openapi-spec=NEW_API_DEFINITION \
    --project=PROJECT_ID --backend-auth-service-account=SERVICE_ACCOUNT_EMAIL
    例:
    gcloud api-gateway api-configs create my-config-key \
      --api=my-api --openapi-spec=openapi2-functions.yaml \
      --project=my-project --backend-auth-service-account=0000000000000compute@developer.gserviceaccount.com
  4. 次のコマンドを実行して、新しい API 構成で既存のゲートウェイを更新します。
    gcloud api-gateway gateways update GATEWAY_ID \
      --api=API_ID --api-config=NEW_CONFIG_ID \
      --location=GCP_REGION --project=PROJECT_ID
    例:
    gcloud api-gateway gateways update my-gateway \
      --api=my-api --api-config=my-config-key \
      --location=us-central1 --project=my-project

API キーのテスト

変更した API を作成してデプロイしたら、API にリクエストを送信してみてください。

次の curl コマンドを入力します。ここで、

  • DEFAULT_HOSTNAME は、デプロイするゲートウェイ URL のホスト名の部分を指定します。
  • hello は、API 構成で指定されたパスです。
curl https://DEFAULT_HOSTNAME/hello

次に例を示します。

curl https://my-gateway-a12bcd345e67f89g0h.uc.gateway.dev/hello

これにより次のエラーが発生するはずです。

UNAUTHENTICATED:Method doesn't allow unregistered callers (callers without established identity). Please use API Key or other form of API consumer identity to call this API.

今度は次の curl コマンドを入力します。ここで、

  • DEFAULT_HOSTNAME は、デプロイするゲートウェイ URL のホスト名の部分を指定します。
  • hello は、API 構成で指定されたパスです。
  • API_KEY は、前の手順で作成した API キーを指定します。
curl https://DEFAULT_HOSTNAME/hello?key=API_KEY

API からのレスポンスに Hello World! が表示されます。

これで完了です。これで API バックエンドは API Gateway で正常に保護されました。追加の API キーを生成して、新しい API クライアントのオンボーディングを開始できます。

クリーンアップ

このクイックスタートで使用したリソースについて、Google Cloud アカウントに課金されないようにするには、次の操作を行います。

このチュートリアルで使用した Google Cloud プロジェクトの削除もできます。

次のステップ