クイックスタート: gcloud CLI を使用してサービスへのトラフィックを保護する
このページでは、API Gateway に API をデプロイして、バックエンド サービスへのトラフィックを保護する方法について説明します。
Google Cloud CLI を使用して Cloud Run functions でバックエンド サービスにアクセスする新しい API をデプロイするには、次の手順に沿って操作します。このクイックスタートでは、API キーを使用してバックエンドを不正アクセスから保護する方法についても説明します。
始める前に
Google Cloud コンソールで [ダッシュボード] ページに移動し、 Google Cloud プロジェクトを選択または作成します。
お支払いが有効になっていることを確認します。
Google Cloud CLI がダウンロードされ、マシンにインストールされていることを確認します。
gcloudコンポーネントを更新します。gcloud components update
デフォルト プロジェクトを設定します。PROJECT_ID は、実際の Google Cloud プロジェクト ID に置き換えます。
gcloud config set project PROJECT_ID
必要なサービスを有効にする
API Gateway では、次の Google Cloud サービスを有効にする必要があります。
| 名前 | サービス名 |
|---|---|
| API Gateway API | apigateway.googleapis.com |
| Service Management API | servicemanagement.googleapis.com |
| Service Control API | servicecontrol.googleapis.com |
必要なサービスを有効にするには:
Google Cloud コンソール
Google Cloud コンソールで、[API とサービス> API ライブラリ] ページに移動します。
- [API ライブラリ] ページの検索バーに、必要な API 名を入力します。
- 検索結果で、API ページを選択します。
- API ページで、[有効にする] をクリックします。
- 上記の表に記載されているサービスごとに、この手順を繰り返します。
Google Cloud CLI
次のコマンドを使用して、サービスを有効にします。
gcloud services enable apigateway.googleapis.comgcloud services enable servicemanagement.googleapis.comgcloud services enable servicecontrol.googleapis.com
gcloud サービスの詳細については、gcloud サービスをご覧ください。
API バックエンドをデプロイする
API ゲートウェイは、デプロイされたバックエンド サービスの前に配置され、すべての受信リクエストを処理します。このクイックスタートでは、API Gateway は、以下に示す Node.js 関数を含む helloGET という名前の Cloud Run functions のバックエンドに受信呼び出しをルーティングします。
const functions = require('@google-cloud/functions-framework'); // Register an HTTP function with the Functions Framework that will be executed // when you make an HTTP request to the deployed function's endpoint. functions.http('helloGET', (req, res) => { res.send('Hello World!'); });
クイックスタート: Google Cloud CLI で Cloud Run functions の関数をデプロイするの手順に沿って、サンプルの Cloud Run functions コードをダウンロードし、Cloud Run functions のバックエンド サービスをデプロイします。このクイックスタートで説明するように、管理者はアカウントと Cloud Build サービス アカウントに追加のロールを付与する必要があります。
Cloud Run functions のデプロイ時に表示されるサービス URL をコピーします。これは、次の手順で API 構成を作成するときに必要になります。
API を作成する
これで、API Gateway で API を作成する準備が整いました。
次のコマンドを入力します。ここで、
- API_ID は API の名前を指定します。API の命名ガイドラインについては、API ID の要件をご覧ください。
gcloud api-gateway apis create API_ID
次に例を示します。
gcloud api-gateway apis create my-api
- API_ID は API の名前を指定します。API の命名ガイドラインについては、API ID の要件をご覧ください。
正常に完了したら、次のコマンドを使用して新しい API の詳細を表示できます。
gcloud api-gateway apis describe API_ID
例:
gcloud api-gateway apis describe my-api
このコマンドを実行すると、次のようなフィード レスポンスが返されます。
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 バックエンドへのトラフィックを API ゲートウェイで管理する前に、API 構成が必要です。
特殊なアノテーションを含む OpenAPI 説明を使用して API 構成を作成し、選択した API Gateway の動作を定義できます。サポートされている OpenAPI 拡張機能の詳細については、以下をご覧ください。
このクイックスタートで使用される OpenAPI の説明には、Cloud Run functions のバックエンドへの転送手順が含まれています。
OpenAPI 2.0
# openapi-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: SERVICE_URL/helloGET responses: '200': description: A successful response schema: type: string
OpenAPI 3.x
# openapi-functions.yaml openapi: 3.0.4 info: title: API_ID optional-string description: Sample API on API Gateway with a Google Cloud Functions backend version: 1.0.0 # Define reusable components in x-google-api-management x-google-api-management: backends: functions_backend: address: SERVICE_URL/helloGET pathTranslation: APPEND_PATH_TO_ADDRESS protocol: "http/1.1" # Apply the backend configuration by referencing it by name. Set at the root so this applies to all operations unless overridden. x-google-backend: functions_backend paths: /hello: get: summary: Greet a user operationId: hello responses: '200': description: A successful response content: application/json: schema: type: string
この OpenAPI 説明をアップロードして、gcloud CLI を使用して API 構成を作成するには:
コマンドラインから、
openapi-functions.yamlという名前の新しいファイルを作成します。新しく作成したファイルに OpenAPI の説明の内容をコピーして貼り付けます。
ファイルを次のように編集します。
titleフィールドで、API_ID を API の名前に置き換え、optional-string を任意の簡単な説明に置き換えます。このフィールドの値は、この API へのアクセス権を付与する API キーを作成するときに使用されます。addressフィールドで、SERVICE_URL を前の手順でコピーした Cloud Run 関数のバックエンド サービスが実行されている URL に置き換えます。
次のコマンドを入力します。ここで、
- CONFIG_ID は API 構成の名前を指定します。
- API_ID は API の名前を指定します。
- API_DEFINITION には、OpenAPI 仕様のファイル名を指定します。
- SERVICE_ACCOUNT_EMAIL は、認証が構成されたバックエンドのトークン署名に使用されるサービス アカウントを指定します。詳細については、サービス アカウントを構成するをご覧ください。
gcloud api-gateway api-configs create CONFIG_ID \ --api=API_ID --openapi-spec=API_DEFINITION \ --backend-auth-service-account=SERVICE_ACCOUNT_EMAIL
例:
gcloud api-gateway api-configs create my-config \ --api=my-api --openapi-spec=openapi2-functions.yaml \ --backend-auth-service-account=0000000000000-compute@developer.gserviceaccount.com
API 構成がダウンストリームのシステムに伝播される際に、このオペレーションが完了するまでに数分を要する場合があります。 複雑な API 構成の作成が正常に完了するまでに最大 10 分を要する場合があります。
API 構成が作成されたら、次のコマンドを実行して詳細を表示できます。
gcloud api-gateway api-configs describe CONFIG_ID \ --api=API_ID
例:
gcloud api-gateway api-configs describe my-config \ --api=my-api
出力には、次の例のように 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
説明:
- 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
正常に完了したら、次のコマンドを使用してゲートウェイの詳細を表示します。
gcloud api-gateway gateways describe GATEWAY_ID \ --location=GCP_REGION
例:
gcloud api-gateway gateways describe my-gateway \ --location=us-central1
このコマンドを実行すると、次のようなフィード レスポンスが返されます。
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 キーを使用して API アクセスを保護します。
- API キーをテストする
API キーで API アクセスを制限するもご覧ください。
API キーを作成する
このクイックスタートで使用している Google Cloud プロジェクトに関連付けられた API キーがまだ存在しない場合は、API キーを作成するの説明に沿って追加します。
返されたキー文字列をコピーして安全に保管します。これは、API キーをテストするときに使用するキー値です。
新しい API 構成を作成してデプロイする
API キーを使用して API アクセスを保護する新しい API 構成を作成してデプロイするには:
- サービスを有効にします。次のコマンドを入力します。ここで、
- MANAGED_SERVICE_NAME は、API のデプロイ時に作成されたマネージド サービスの名前を指定します。これは、
gcloud api-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
- MANAGED_SERVICE_NAME は、API のデプロイ時に作成されたマネージド サービスの名前を指定します。これは、
- API 構成の作成に使用される OpenAPI 説明を変更して、すべてのトラフィックに API キー検証セキュリティ ポリシーを適用する手順を含めます。以下に示すように、
securityタイプとsecurityDefinitionsを追加します。OpenAPI 2.0
# 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: SERVICE_URL/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 を構成します。OpenAPI 3.x
# openapi-functions.yaml openapi: 3.0.4 info: title: API_ID optional-string description: Sample API on API Gateway with a Google Cloud Functions backend version: 1.0.0 # Define reusable components in x-google-api-management x-google-api-management: backends: functions_backend: address: SERVICE_URL/helloGET pathTranslation: APPEND_PATH_TO_ADDRESS protocol: "http/1.1" # Apply the backend configuration by referencing it by name. Set at the root so this applies to all operations unless overridden. x-google-backend: functions_backend components: # This section configures basic authentication with an API key. securitySchemes: google_api_key: type: apiKey name: x-api-key in: header security: - google_api_key: [] paths: /hello: get: summary: Greet a user operationId: hello responses: '200': description: A successful response content: application/json: schema: type: string
securitySchemesは、仕様で定義されているすべてのパスへのアクセスをリクエストするときに、keyという名前のクエリ パラメータとして渡される API キーを要求するように API を構成します。 - 次のコマンドを使用して、変更した OpenAPI 仕様で新しい API 構成を作成します。
次に例を示します。gcloud api-gateway api-configs create NEW_CONFIG_ID \ --api=API_ID --openapi-spec=NEW_API_DEFINITION \ --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
- 次のコマンドを実行して、新しい API 構成で既存のゲートウェイを更新します。
次に例を示します。gcloud api-gateway gateways update GATEWAY_ID \ --api=API_ID --api-config=NEW_CONFIG_ID \ --location=GCP_REGION
gcloud api-gateway gateways update my-gateway \ --api=my-api --api-config=my-config-key \ --location=us-central1
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 プロジェクトの削除もできます。
次のステップ
- API Gateway についての詳細を確認する
- 開発環境を構成するを確認する
- サービス間の認証について確認する