快速入門導覽課程:使用 gcloud CLI 保護傳送至服務的流量
本頁面說明如何在 API Gateway 上部署 API,確保後端服務的流量安全。
請按照下列步驟,使用 Google Cloud CLI 部署新 API,存取 Cloud Run functions 上的後端服務。本快速入門導覽課程也會說明如何使用 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 服務:
| 名稱 | 標題 |
|---|---|
apigateway.googleapis.com |
API Gateway API |
servicemanagement.googleapis.com |
Service Management API |
servicecontrol.googleapis.com |
Service Control API |
請使用下列指令啟用這些服務:
gcloud services enable apigateway.googleapis.comgcloud services enable servicemanagement.googleapis.comgcloud services enable servicecontrol.googleapis.com
如要進一步瞭解 gcloud 服務,請參閱
gcloud 服務。
部署 API 後端
API Gateway 位於已部署的後端服務前方,負責處理所有傳入的要求。在本快速入門導覽課程中,API 閘道會將來電轉送至名為 helloGET 的 Cloud Run 函式後端,其中包含的 Node.js 函式如下:
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 函式程式碼,並部署 Cloud Run 函式後端服務。如本快速入門指南所述,管理員必須將其他角色授予您的帳戶和 Cloud Build 服務帳戶。
複製部署 Cloud Run 函式時顯示的「Service 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 Gateway 必須先取得 API 設定,才能管理傳送至部署 API 後端的流量。
您可以使用包含特殊註解的 OpenAPI 說明建立 API 設定,定義所選的 API Gateway 行為。如要進一步瞭解支援的 OpenAPI 擴充功能,請參閱下列說明:
本快速入門導覽課程使用的 OpenAPI 說明包含 Cloud Run 函式後端的轉送指示:
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 函式後端服務的執行網址 (先前步驟中複製的網址)。
- 在
輸入下列指令,其中:
- 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 設定最多可能需要十分鐘。
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 的外部網址。
執行下列指令,將您剛建立的 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 屬性的值。這是閘道網址的主機名稱部分,您會在下一個步驟中用來測試部署作業。
測試 API 部署作業
現在,您可以使用部署閘道時產生的網址來傳送要求至 API。
輸入下列 curl 指令,其中:
- DEFAULT_HOSTNAME 指定您在上一個步驟中複製的已部署閘道網址主機名稱部分。
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會將您的 API 設定為要求以名為key的查詢參數形式傳遞 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會將您的 API 設定為要求以名為key的查詢參數形式傳遞 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 之後,請嘗試提出要求。
輸入下列 curl 指令,其中:
- DEFAULT_HOSTNAME 指定您在上一個步驟中複製的已部署閘道網址主機名稱部分。
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 指定您在上一個步驟中複製的已部署閘道網址主機名稱部分。
hello是 API 設定中指定的路徑。- API_KEY 指定您在前一個步驟中建立的 API 金鑰。
curl https://DEFAULT_HOSTNAME/hello?key=API_KEY
現在您應該會在 API 的回應中看到 Hello World!。
恭喜!您已成功使用 API Gateway 保護 API 後端。現在您可以產生其他 API 金鑰,開始加入新的 API 用戶端。
清除所用資源
如要避免系統向您的 Google Cloud 帳戶收取本快速入門導覽課程所用資源的費用,請採取下列行動:
或者,您也可以刪除 Google Cloud 本教學課程中使用的專案。
後續步驟
- 進一步瞭解 API Gateway
- 逐步完成「設定開發環境」一節
- 瞭解服務之間的驗證