管理 API 金鑰

本頁說明如何建立、編輯及限制 API 金鑰。如要瞭解如何使用 API 金鑰存取 Google API,請參閱「使用 API 金鑰存取 API」。

API 金鑰簡介

API 金鑰有兩種類型:標準 API 金鑰,以及已繫結至服務帳戶的 API 金鑰。

標準 API 金鑰

標準 API 金鑰可讓您將要求與專案建立關聯,以便處理帳單和配額。使用標準 API 金鑰 (未繫結至服務帳戶的 API 金鑰) 存取 API 時,API 金鑰不會識別實體。如果沒有主體,要求就無法使用 Identity and Access Management (IAM) 來檢查呼叫端是否有權執行要求的作業。

標準 API 金鑰可與任何接受 API 金鑰的 API 搭配使用,除非金鑰已新增 API 限制。標準 API 金鑰無法用於不接受 API 金鑰的服務,包括快捷模式

已繫結至服務帳戶的 API 金鑰

繫結至服務帳戶的 API 金鑰會提供服務帳戶向要求提供的身分和授權。當您使用已繫結至服務帳戶的 API 金鑰存取 API 時,系統會以您使用繫結的服務帳戶提出要求的方式處理要求。

預設的機構政策限制會禁止將金鑰繫結至服務帳戶。如要變更這項設定,請參閱「啟用金鑰與服務帳戶的繫結」一文。

API 金鑰元件

API 金鑰包含下列元件,可讓您管理及使用金鑰:

字串
API 金鑰字串是加密字串,例如 AIzaSyDaGmWKa4JsXZ-HjGw7ISLn_3namBGewQe。使用 API 金鑰存取 API 時,請一律使用金鑰的字串。API 金鑰沒有相關聯的 JSON 檔案。
ID
Google Cloud 管理工具會使用 API 金鑰 ID 來識別金鑰。金鑰 ID 無法用於存取 API。您可以在 Google Cloud 控制台的金鑰編輯頁面網址中找到金鑰 ID。您也可以使用 Google Cloud CLI 列出專案中的金鑰,藉此取得金鑰 ID。
顯示名稱
顯示名稱是金鑰的選用描述性名稱,您可以在建立或更新金鑰時設定。
已繫結的服務帳戶
與服務帳戶繫結的 API 金鑰會包含服務帳戶的電子郵件地址。

事前準備

請完成下列工作,才能使用本頁面的範例。

設定驗證方法

Select the tab for how you plan to use the samples on this page:

Console

When you use the Google Cloud console to access Google Cloud services and APIs, you don't need to set up authentication.

gcloud

In the Google Cloud console, activate Cloud Shell.

Activate Cloud Shell

At the bottom of the Google Cloud console, a Cloud Shell session starts and displays a command-line prompt. Cloud Shell is a shell environment with the Google Cloud CLI already installed and with values already set for your current project. It can take a few seconds for the session to initialize.

C++

To use the C++ samples on this page in a local development environment, install and initialize the gcloud CLI, and then set up Application Default Credentials with your user credentials.

  1. Install the Google Cloud CLI.

  2. If you're using an external identity provider (IdP), you must first sign in to the gcloud CLI with your federated identity.

  3. To initialize the gcloud CLI, run the following command:

    gcloud init
  4. If you're using a local shell, then create local authentication credentials for your user account:

    gcloud auth application-default login

    You don't need to do this if you're using Cloud Shell.

    If an authentication error is returned, and you are using an external identity provider (IdP), confirm that you have signed in to the gcloud CLI with your federated identity.

  5. For more information, see Set up ADC for a local development environment in the Google Cloud authentication documentation.

Java

To use the Java samples on this page in a local development environment, install and initialize the gcloud CLI, and then set up Application Default Credentials with your user credentials.

  1. Install the Google Cloud CLI.

  2. If you're using an external identity provider (IdP), you must first sign in to the gcloud CLI with your federated identity.

  3. To initialize the gcloud CLI, run the following command:

    gcloud init
  4. If you're using a local shell, then create local authentication credentials for your user account:

    gcloud auth application-default login

    You don't need to do this if you're using Cloud Shell.

    If an authentication error is returned, and you are using an external identity provider (IdP), confirm that you have signed in to the gcloud CLI with your federated identity.

  5. For more information, see Set up ADC for a local development environment in the Google Cloud authentication documentation.

Python

To use the Python samples on this page in a local development environment, install and initialize the gcloud CLI, and then set up Application Default Credentials with your user credentials.

  1. Install the Google Cloud CLI.

  2. If you're using an external identity provider (IdP), you must first sign in to the gcloud CLI with your federated identity.

  3. To initialize the gcloud CLI, run the following command:

    gcloud init
  4. If you're using a local shell, then create local authentication credentials for your user account:

    gcloud auth application-default login

    You don't need to do this if you're using Cloud Shell.

    If an authentication error is returned, and you are using an external identity provider (IdP), confirm that you have signed in to the gcloud CLI with your federated identity.

  5. For more information, see Set up ADC for a local development environment in the Google Cloud authentication documentation.

REST

To use the REST API samples on this page in a local development environment, you use the credentials you provide to the gcloud CLI.

    After installing the Google Cloud CLI, initialize it by running the following command:

    gcloud init

    If you're using an external identity provider (IdP), you must first sign in to the gcloud CLI with your federated identity.

For more information, see Authenticate for using REST in the Google Cloud authentication documentation.

必要的角色

如要取得管理 API 金鑰所需的權限,請要求管理員為您授予專案的下列身分與存取權管理角色:

如要進一步瞭解如何授予角色,請參閱「管理專案、資料夾和機構的存取權」。

您或許還可透過自訂角色或其他預先定義的角色取得必要權限。

啟用金鑰繫結至服務帳戶

您必須先將 constraints/iam.managed.disableServiceAccountApiKeyCreation 機構政策限制設為 false,才能將 API 金鑰繫結至服務帳戶。變更機構政策時,必須有相關聯的機構資源。不支援不屬於任何機構的專案。

如要變更政策限制,請完成下列操作說明。

主控台

  1. 在 Google Cloud 控制台中,前往「Organization policies」(機構政策) 頁面。

    前往「機構政策」

  2. 切換至要變更政策的機構、資料夾或專案。

  3. 在「Filter」方塊中輸入 Block service,然後按一下篩選器名稱「Block service account API key bindings」

  4. 按一下「管理政策」

  5. 在「政策來源」部分,選取「覆寫父項政策」

  6. 按一下「新增規則」,然後將「強制執行」設為「關閉」

  7. 按一下 [完成]

  8. 選用步驟:點選「測試變更」,深入瞭解套用提出的政策之後,可能會發生哪些違規或服務中斷情形。

  9. 按一下「設定政策」

gcloud

  1. 建立名為 spec.yaml 的檔案,並在其中加入下列內容:

    name: SCOPE/SCOPE_ID/policies/iam.managed.disableServiceAccountApiKeyCreation
    spec:
      rules:
      - enforce: false
    

    提供以下這些值:

    • SCOPEorganizationsfoldersprojects

    • SCOPE_ID:視 SCOPE 而定,是指組織政策套用的機構、資料夾或專案 ID。

  2. 執行下列 gcloud 指令,允許將 API 金鑰繫結至服務帳戶:

    gcloud org-policies set-policy spec.yaml \
        --update-mask spec
    

建立 API 金鑰

如要建立 API 金鑰,請使用下列其中一種方式:

主控台

  1. 在 Google Cloud 控制台中,前往「憑證」頁面:

    前往「憑證」

  2. 按一下「建立憑證」,然後在選單中選取「API 金鑰」

  3. 選用:如要將 API 金鑰繫結至服務帳戶,請選取「透過服務帳戶驗證 API 呼叫」核取方塊,然後按一下「選取服務帳戶」,選取要繫結至金鑰的服務帳戶。

    詳情請參閱「繫結至服務帳戶的 API 金鑰」。

  4. 新增 API 金鑰限制。

    限制 API 金鑰是最佳做法。詳情請參閱「套用 API 金鑰限制」一節。

  5. 按一下「建立」,「建立的 API 金鑰」對話方塊會顯示新建立金鑰的字串。

gcloud

您可以使用 gcloud services api-keys create 指令建立 API 金鑰。

DISPLAY_NAME 替換為描述金鑰的名稱。

 gcloud services api-keys create \
     --display-name=DISPLAY_NAME

選用:如要將 API 金鑰繫結至服務帳戶,請改用 gcloud beta 搭配 --service-account 標記:

 gcloud beta services api-keys create \
     --display-name=DISPLAY_NAME \
     --service-account=SERVICE_ACCOUNT_EMAIL_ADDRESS

詳情請參閱「繫結至服務帳戶的 API 金鑰」。

C++

如要執行這個範例,您必須安裝 API 金鑰用戶端程式庫

#include "google/cloud/apikeys/v2/api_keys_client.h"
#include "google/cloud/location.h"

google::api::apikeys::v2::Key CreateApiKey(
    google::cloud::apikeys_v2::ApiKeysClient client,
    google::cloud::Location location, std::string display_name) {
  google::api::apikeys::v2::CreateKeyRequest request;
  request.set_parent(location.FullName());
  request.mutable_key()->set_display_name(std::move(display_name));
  // As an example, restrict the API key's scope to the Natural Language API.
  request.mutable_key()->mutable_restrictions()->add_api_targets()->set_service(
      "language.googleapis.com");

  // Create the key, blocking on the result.
  auto key = client.CreateKey(request).get();
  if (!key) throw std::move(key.status());
  std::cout << "Successfully created an API key: " << key->name() << "\n";

  // For authenticating with the API key, use the value in `key->key_string()`.

  // The API key's resource name is the value in `key->name()`. Use this to
  // refer to the specific key in a `GetKey()` or `DeleteKey()` RPC.
  return *key;
}

Java

如要執行此範例,您必須安裝 google-cloud-apikeys 用戶端程式庫


import com.google.api.apikeys.v2.ApiKeysClient;
import com.google.api.apikeys.v2.ApiTarget;
import com.google.api.apikeys.v2.CreateKeyRequest;
import com.google.api.apikeys.v2.Key;
import com.google.api.apikeys.v2.LocationName;
import com.google.api.apikeys.v2.Restrictions;
import java.io.IOException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

public class CreateApiKey {

  public static void main(String[] args)
      throws IOException, ExecutionException, InterruptedException, TimeoutException {
    // TODO(Developer): Before running this sample,
    //  1. Replace the variable(s) below.
    //  2. Set up ADC as described in https://cloud.google.com/docs/authentication/external/set-up-adc
    //  3. Make sure you have the necessary permission to create API keys.
    String projectId = "GOOGLE_CLOUD_PROJECT_ID";

    createApiKey(projectId);
  }

  // Creates an API key.
  public static void createApiKey(String projectId)
      throws IOException, ExecutionException, InterruptedException, TimeoutException {
    // Initialize client that will be used to send requests. This client only needs to be created
    // once, and can be reused for multiple requests. After completing all of your requests, call
    // the `apiKeysClient.close()` method on the client to safely
    // clean up any remaining background resources.
    try (ApiKeysClient apiKeysClient = ApiKeysClient.create()) {

      Key key = Key.newBuilder()
          .setDisplayName("My first API key")
          // Set the API key restriction.
          // You can also set browser/ server/ android/ ios based restrictions.
          // For more information on API key restriction, see:
          // https://cloud.google.com/docs/authentication/api-keys#api_key_restrictions
          .setRestrictions(Restrictions.newBuilder()
              // Restrict the API key usage by specifying the target service and methods.
              // The API key can only be used to authenticate the specified methods in the service.
              .addApiTargets(ApiTarget.newBuilder()
                  .setService("translate.googleapis.com")
                  .addMethods("translate.googleapis.com.TranslateText")
                  .build())
              .build())
          .build();

      // Initialize request and set arguments.
      CreateKeyRequest createKeyRequest = CreateKeyRequest.newBuilder()
          // API keys can only be global.
          .setParent(LocationName.of(projectId, "global").toString())
          .setKey(key)
          .build();

      // Make the request and wait for the operation to complete.
      Key result = apiKeysClient.createKeyAsync(createKeyRequest).get(3, TimeUnit.MINUTES);

      // For authenticating with the API key, use the value in "result.getKeyString()".
      // To restrict the usage of this API key, use the value in "result.getName()".
      System.out.printf("Successfully created an API key: %s", result.getName());
    }
  }
}

Python

如要執行這個範例,您必須安裝 API 金鑰用戶端程式庫


from google.cloud import api_keys_v2
from google.cloud.api_keys_v2 import Key


def create_api_key(project_id: str, suffix: str) -> Key:
    """
    Creates and restrict an API key. Add the suffix for uniqueness.

    TODO(Developer):
    1. Before running this sample,
      set up ADC as described in https://cloud.google.com/docs/authentication/external/set-up-adc
    2. Make sure you have the necessary permission to create API keys.

    Args:
        project_id: Google Cloud project id.

    Returns:
        response: Returns the created API Key.
    """
    # Create the API Keys client.
    client = api_keys_v2.ApiKeysClient()

    key = api_keys_v2.Key()
    key.display_name = f"My first API key - {suffix}"

    # Initialize request and set arguments.
    request = api_keys_v2.CreateKeyRequest()
    request.parent = f"projects/{project_id}/locations/global"
    request.key = key

    # Make the request and wait for the operation to complete.
    response = client.create_key(request=request).result()

    print(f"Successfully created an API key: {response.name}")
    # For authenticating with the API key, use the value in "response.key_string".
    # To restrict the usage of this API key, use the value in "response.name".
    return response

REST

您可以使用 keys.create 方法建立 API 金鑰。這項要求會傳回長時間執行作業;您必須輪詢該作業,才能取得新金鑰的資訊。

替換下列值:

  • DISPLAY_NAME:選用。鍵的描述性名稱。
  • PROJECT_ID:您的 Google Cloud 專案 ID 或名稱。
curl -X POST \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "Content-Type: application/json; charset=utf-8" \
-d {'"displayName" : "DISPLAY_NAME"'} \
"https://apikeys.googleapis.com/v2/projects/PROJECT/locations/global/keys"

選用:如要將 API 金鑰繫結至服務帳戶,請使用下列指令:

curl -X POST \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "Content-Type: application/json; charset=utf-8" \
-d {'"displayName" : "DISPLAY_NAME",
     "serviceAccountEmail" : "SERVICE_ACCOUNT_EMAIL"'} \
"https://apikeys.googleapis.com/v2/projects/PROJECT/locations/global/keys"

詳情請參閱「已繫結至服務帳戶的 API 金鑰」。

如要進一步瞭解如何使用 REST API 建立 API 金鑰,請參閱 API 金鑰 API 說明文件中的「建立 API 金鑰」一節。

套用 API 金鑰限制

根據預設,API 金鑰不會受到限制。未設限制的金鑰不安全,因為任何人都能在任何地方使用這類金鑰。對於實際工作環境應用程式,您應同時設定應用程式限制API 限制

新增應用程式限制

應用程式限制會指定哪些網站、IP 位址或應用程式可以使用 API 金鑰。

您一次只能套用一種應用程式限制類型。請根據應用程式類型選擇限制類型:

選項 應用程式類型 附註
HTTP 參照網址 網頁應用程式 指定可使用金鑰的網站。
IP 位址 由特定伺服器呼叫的應用程式 指定可使用金鑰的伺服器或 Cron 工作。這是將 API 金鑰繫結至服務帳戶時唯一適用的限制。
Android 應用程式 Android 應用程式 指定可使用金鑰的 Android 應用程式。
iOS 應用程式 iOS 應用程式 指定可使用此金鑰的 iOS 套件。

HTTP 參照網址

如要限制可使用 API 金鑰的網站,請新增一或多個 HTTP 參照網址限制。

您可以使用萬用字元 (*) 取代子網域或路徑,但不得在網址中間插入萬用字元。舉例來說,*.example.com 是有效的值,且接受結尾為 .example.com 的所有網站。不過,mysubdomain*.example.com 並非有效的限制條件。

通訊埠編號可納入 HTTP 參照網址限制。如果您加入連接埠號碼,系統只會比對使用該連接埠的請求。如果您未指定通訊埠編號,系統會比對任何通訊埠編號的請求。

下表列出一些情境和瀏覽器限制的範例:

情境 限制
允許特定網址 新增含有確切路徑的網址。例如:
www.example.com/path
www.example.com/path/path

部分瀏覽器會實作 參照網址政策,只傳送跨來源要求的原始網址。使用這些瀏覽器的使用者無法使用含有網頁專屬網址限制的金鑰。

允許網站上的任何網址 您必須在 allowedReferers 清單中設定兩個網址。
  1. 網域的網址 (不含子網域),路徑中含有萬用字元。例如:
    example.com/*
  2. 第二個網址包含子網域萬用字元和路徑萬用字元。例如:
    *.example.com/*
允許單一子網域或裸網域中的任何網址

您必須在 allowedReferers 清單中設定兩個網址,才能允許整個網域:

  1. 網域的網址,不含結尾斜線。例如:
    www.example.com
    sub.example.com
    example.com
  2. 網域的第二個網址,其中包含路徑的萬用字元。例如:
    www.example.com/*
    sub.example.com/*
    example.com/*

如要將 API 金鑰的使用範圍限制在特定網站,請使用下列任一選項:

主控台

  1. 在 Google Cloud 控制台中,前往「憑證」頁面:

    前往「憑證」

  2. 按一下要設定限制的 API 金鑰名稱。

  3. 在「應用程式限制」部分中,選取「HTTP 參照網址」

  4. 針對每項要新增的限制,請按一下「新增項目」,輸入限制,然後按一下「完成」

  5. 按一下「儲存」儲存變更,然後返回 API 金鑰清單。

gcloud

  1. 取得要限制的金鑰 ID。

    ID 與顯示名稱或索引鍵字串不同。您可以使用 gcloud services api-keys list 指令列出專案中的金鑰,藉此取得 ID。

  2. 使用 gcloud services api-keys update 指令為 API 金鑰新增 HTTP 參照網址限制。

    替換下列值:

    • KEY_ID:您要限制的鍵 ID。
    • ALLOWED_REFERRER_1:您的 HTTP 參照網址限制。

      您可以視需要新增多項限制,並使用半形逗號分隔。您必須使用更新指令提供所有參照來源限制;提供的參照來源限制會取代金鑰上任何現有的參照來源限制。

    gcloud services api-keys update KEY_ID \
     --allowed-referrers="ALLOWED_REFERRER_1"

Java

如要執行此範例,您必須安裝 google-cloud-apikeys 用戶端程式庫


import com.google.api.apikeys.v2.ApiKeysClient;
import com.google.api.apikeys.v2.BrowserKeyRestrictions;
import com.google.api.apikeys.v2.Key;
import com.google.api.apikeys.v2.Restrictions;
import com.google.api.apikeys.v2.UpdateKeyRequest;
import com.google.protobuf.FieldMask;
import java.io.IOException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

public class RestrictApiKeyHttp {

  public static void main(String[] args)
      throws IOException, ExecutionException, InterruptedException, TimeoutException {
    // TODO(Developer): Before running this sample,
    //  1. Replace the variable(s) below.
    String projectId = "GOOGLE_CLOUD_PROJECT_ID";

    // ID of the key to restrict. This ID is auto-created during key creation.
    // This is different from the key string. To obtain the key_id,
    // you can also use the lookup api: client.lookupKey()
    String keyId = "key_id";

    restrictApiKeyHttp(projectId, keyId);
  }

  // Restricts an API key. To restrict the websites that can use your API key,
  // you add one or more HTTP referrer restrictions.
  public static void restrictApiKeyHttp(String projectId, String keyId)
      throws IOException, ExecutionException, InterruptedException, TimeoutException {
    // Initialize client that will be used to send requests. This client only needs to be created
    // once, and can be reused for multiple requests. After completing all of your requests, call
    // the `apiKeysClient.close()` method on the client to safely
    // clean up any remaining background resources.
    try (ApiKeysClient apiKeysClient = ApiKeysClient.create()) {

      // Restrict the API key usage to specific websites by adding them
      // to the list of allowed_referrers.
      Restrictions restrictions = Restrictions.newBuilder()
          .setBrowserKeyRestrictions(BrowserKeyRestrictions.newBuilder()
              .addAllowedReferrers("www.example.com/*")
              .build())
          .build();

      Key key = Key.newBuilder()
          .setName(String.format("projects/%s/locations/global/keys/%s", projectId, keyId))
          // Set the restriction(s).
          // For more information on API key restriction, see:
          // https://cloud.google.com/docs/authentication/api-keys
          .setRestrictions(restrictions)
          .build();

      // Initialize request and set arguments.
      UpdateKeyRequest updateKeyRequest = UpdateKeyRequest.newBuilder()
          .setKey(key)
          .setUpdateMask(FieldMask.newBuilder().addPaths("restrictions").build())
          .build();

      // Make the request and wait for the operation to complete.
      Key result = apiKeysClient.updateKeyAsync(updateKeyRequest).get(3, TimeUnit.MINUTES);

      // For authenticating with the API key, use the value in "result.getKeyString()".
      System.out.printf("Successfully updated the API key: %s", result.getName());
    }
  }
}

Python

如要執行這個範例,您必須安裝 API 金鑰用戶端程式庫


from google.cloud import api_keys_v2
from google.cloud.api_keys_v2 import Key


def restrict_api_key_http(project_id: str, key_id: str) -> Key:
    """
    Restricts an API key. To restrict the websites that can use your API key,
    you add one or more HTTP referrer restrictions.

    TODO(Developer): Replace the variables before running this sample.

    Args:
        project_id: Google Cloud project id.
        key_id: ID of the key to restrict. This ID is auto-created during key creation.
            This is different from the key string. To obtain the key_id,
            you can also use the lookup api: client.lookup_key()

    Returns:
        response: Returns the updated API Key.
    """

    # Create the API Keys client.
    client = api_keys_v2.ApiKeysClient()

    # Restrict the API key usage to specific websites by adding them to the list of allowed_referrers.
    browser_key_restrictions = api_keys_v2.BrowserKeyRestrictions()
    browser_key_restrictions.allowed_referrers = ["www.example.com/*"]

    # Set the API restriction.
    # For more information on API key restriction, see:
    # https://cloud.google.com/docs/authentication/api-keys
    restrictions = api_keys_v2.Restrictions()
    restrictions.browser_key_restrictions = browser_key_restrictions

    key = api_keys_v2.Key()
    key.name = f"projects/{project_id}/locations/global/keys/{key_id}"
    key.restrictions = restrictions

    # Initialize request and set arguments.
    request = api_keys_v2.UpdateKeyRequest()
    request.key = key
    request.update_mask = "restrictions"

    # Make the request and wait for the operation to complete.
    response = client.update_key(request=request).result()

    print(f"Successfully updated the API key: {response.name}")
    # Use response.key_string to authenticate.
    return response

REST

  1. 取得要限制的金鑰 ID。

    ID 與顯示名稱或索引鍵字串不同。您可以使用 keys.list 方法取得 ID。這個 ID 會列在回應的 uid 欄位中。

    PROJECT_ID 替換為您的 Google Cloud 專案 ID 或名稱。

    curl -X GET \
    -H "Authorization: Bearer $(gcloud auth print-access-token)" \
    "https://apikeys.googleapis.com/v2/projects/PROJECT_ID/locations/global/keys/"
  2. 使用 keys.patch 方法,為 API 金鑰新增 HTTP 參照網址限制。

    這項要求會傳回長時間執行作業;您必須輪詢作業,才能瞭解作業完成的時間並取得作業狀態。

    替換下列值:

    • ALLOWED_REFERRER_1:您的 HTTP 參照網址限制。

      您可以視需要新增多項限制,並使用半形逗號分隔。您必須在要求中提供所有參照網址限制;提供的參照網址限制會取代金鑰上任何現有的參照網址限制。

    • PROJECT_ID:您的 Google Cloud 專案 ID 或名稱。

    • KEY_ID:您要限制的鍵 ID。

    curl -X PATCH \
    -H "Authorization: Bearer $(gcloud auth print-access-token)" \
    -H "Content-Type: application/json; charset=utf-8" \
    --data '{
    "restrictions" : {
    "browserKeyRestrictions": {
      "allowedReferrers": ["ALLOWED_REFERRER_1"]
    }
    }
    }' \
    "https://apikeys.googleapis.com/v2/projects/PROJECT_ID/locations/global/keys/KEY_ID?updateMask=restrictions"

如要進一步瞭解如何使用 REST API 為金鑰新增 HTTP 參照網址限制,請參閱 API 金鑰 API 說明文件中的「新增瀏覽器限制」一節。

IP 位址

您可以指定一或多個呼叫端 IP 位址 (例如網路伺服器或 cron 工作),允許這類呼叫端使用您的 API 金鑰。您可以使用下列任一格式指定 IP 位址:

  • IPv4 (198.51.100.1)
  • IPv6 (2001:db8::1)
  • 使用 CIDR 標記法的子網路 (198.51.100.0/242001:db8::/64)

伺服器限制不支援使用 localhost

如要將 API 金鑰的使用限制在特定 IP 位址,請使用下列任一選項:

主控台

  1. 在 Google Cloud 控制台中,前往「憑證」頁面:

    前往「憑證」

  2. 按一下要設定限制的 API 金鑰名稱。

  3. 在「應用程式限制」區塊中,選取「IP 位址」

  4. 針對每個要新增的 IP 位址,按一下「新增項目」,輸入地址,然後按一下「完成」

  5. 按一下「儲存」儲存變更,然後返回 API 金鑰清單。

gcloud

  1. 取得要限制的金鑰 ID。

    ID 與顯示名稱或索引鍵字串不同。您可以使用 gcloud services api-keys list 指令列出專案中的金鑰,藉此取得 ID。

  2. 使用 gcloud services api-keys update 指令,為 API 金鑰新增伺服器 (IP 位址) 限制。

    替換下列值:

    • KEY_ID:您要限制的鍵 ID。
    • ALLOWED_IP_ADDR_1:您的允許 IP 位址。

      您可以視需要新增任意數量的 IP 位址,並使用半形逗號分隔各個位址。

    gcloud services api-keys update KEY_ID \
    --allowed-ips="ALLOWED_IP_ADDR_1"

Java

如要執行此範例,您必須安裝 google-cloud-apikeys 用戶端程式庫


import com.google.api.apikeys.v2.ApiKeysClient;
import com.google.api.apikeys.v2.Key;
import com.google.api.apikeys.v2.Restrictions;
import com.google.api.apikeys.v2.ServerKeyRestrictions;
import com.google.api.apikeys.v2.UpdateKeyRequest;
import com.google.protobuf.FieldMask;
import java.io.IOException;
import java.util.Arrays;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

public class RestrictApiKeyServer {

  public static void main(String[] args)
      throws IOException, ExecutionException, InterruptedException, TimeoutException {
    // TODO(Developer): Before running this sample,
    //  1. Replace the variable(s) below.
    String projectId = "GOOGLE_CLOUD_PROJECT_ID";

    // ID of the key to restrict. This ID is auto-created during key creation.
    // This is different from the key string. To obtain the key_id,
    // you can also use the lookup api: client.lookupKey()
    String keyId = "key_id";

    restrictApiKeyServer(projectId, keyId);
  }

  // Restricts the API key based on IP addresses. You can specify one or more IP addresses
  // of the callers, for example web servers or cron jobs, that are allowed to use your API key.
  public static void restrictApiKeyServer(String projectId, String keyId)
      throws IOException, ExecutionException, InterruptedException, TimeoutException {
    // Initialize client that will be used to send requests. This client only needs to be created
    // once, and can be reused for multiple requests. After completing all of your requests, call
    // the `apiKeysClient.close()` method on the client to safely
    // clean up any remaining background resources.
    try (ApiKeysClient apiKeysClient = ApiKeysClient.create()) {

      // Restrict the API key usage by specifying the IP addresses.
      // You can specify the IP addresses in IPv4 or IPv6 or a subnet using CIDR notation.
      Restrictions restrictions = Restrictions.newBuilder()
          .setServerKeyRestrictions(ServerKeyRestrictions.newBuilder()
              .addAllAllowedIps(Arrays.asList("198.51.100.0/24", "2000:db8::/64"))
              .build())
          .build();

      Key key = Key.newBuilder()
          .setName(String.format("projects/%s/locations/global/keys/%s", projectId, keyId))
          // Set the restriction(s).
          // For more information on API key restriction, see:
          // https://cloud.google.com/docs/authentication/api-keys
          .setRestrictions(restrictions)
          .build();

      // Initialize request and set arguments.
      UpdateKeyRequest updateKeyRequest = UpdateKeyRequest.newBuilder()
          .setKey(key)
          .setUpdateMask(FieldMask.newBuilder().addPaths("restrictions").build())
          .build();

      // Make the request and wait for the operation to complete.
      Key result = apiKeysClient.updateKeyAsync(updateKeyRequest).get(3, TimeUnit.MINUTES);

      // For authenticating with the API key, use the value in "result.getKeyString()".
      System.out.printf("Successfully updated the API key: %s", result.getName());
    }
  }
}

Python

如要執行這個範例,您必須安裝 API 金鑰用戶端程式庫


from google.cloud import api_keys_v2
from google.cloud.api_keys_v2 import Key


def restrict_api_key_server(project_id: str, key_id: str) -> Key:
    """
    Restricts the API key based on IP addresses. You can specify one or more IP addresses of the callers,
    for example web servers or cron jobs, that are allowed to use your API key.

    TODO(Developer): Replace the variables before running this sample.

    Args:
        project_id: Google Cloud project id.
        key_id: ID of the key to restrict. This ID is auto-created during key creation.
            This is different from the key string. To obtain the key_id,
            you can also use the lookup api: client.lookup_key()

    Returns:
        response: Returns the updated API Key.
    """

    # Create the API Keys client.
    client = api_keys_v2.ApiKeysClient()

    # Restrict the API key usage by specifying the IP addresses.
    # You can specify the IP addresses in IPv4 or IPv6 or a subnet using CIDR notation.
    server_key_restrictions = api_keys_v2.ServerKeyRestrictions()
    server_key_restrictions.allowed_ips = ["198.51.100.0/24", "2000:db8::/64"]

    # Set the API restriction.
    # For more information on API key restriction, see:
    # https://cloud.google.com/docs/authentication/api-keys
    restrictions = api_keys_v2.Restrictions()
    restrictions.server_key_restrictions = server_key_restrictions

    key = api_keys_v2.Key()
    key.name = f"projects/{project_id}/locations/global/keys/{key_id}"
    key.restrictions = restrictions

    # Initialize request and set arguments.
    request = api_keys_v2.UpdateKeyRequest()
    request.key = key
    request.update_mask = "restrictions"

    # Make the request and wait for the operation to complete.
    response = client.update_key(request=request).result()

    print(f"Successfully updated the API key: {response.name}")
    # Use response.key_string to authenticate.
    return response

REST

  1. 取得要限制的金鑰 ID。

    ID 與顯示名稱或索引鍵字串不同。您可以使用 keys.list 方法取得 ID。這個 ID 會列在回應的 uid 欄位中。

    PROJECT_ID 替換為您的 Google Cloud 專案 ID 或名稱。

    curl -X GET \
    -H "Authorization: Bearer $(gcloud auth print-access-token)" \
    "https://apikeys.googleapis.com/v2/projects/PROJECT_ID/locations/global/keys/"
  2. 使用 keys.patch 方法,為 API 金鑰新增伺服器 (IP 位址) 限制。

    這項要求會傳回長時間執行作業;您必須輪詢作業,才能瞭解作業完成的時間並取得作業狀態。

    替換下列值:

    • ALLOWED_IP_ADDR_1:您的允許 IP 位址。

      您可以視需要新增任意數量的 IP 位址,請使用半形逗號分隔限制。您必須在要求中提供所有 IP 位址;提供的參照來源限制會取代金鑰上的任何現有 IP 位址限制。

    • PROJECT_ID:您的 Google Cloud 專案 ID 或名稱。

    • KEY_ID:您要限制的鍵 ID。

    curl -X PATCH \
    -H "Authorization: Bearer $(gcloud auth print-access-token)" \
    -H "Content-Type: application/json; charset=utf-8" \
    --data '{
    "restrictions" : {
      "serverKeyRestrictions": {
        "allowedIps": ["ALLOWED_IP_ADDR_1"]
      }
    }
    }' \
    "https://apikeys.googleapis.com/v2/projects/PROJECT_ID/locations/global/keys/KEY_ID?updateMask=restrictions"

如要進一步瞭解如何使用 REST API 為金鑰新增 IP 位址限制,請參閱 API Keys API 說明文件中的「新增伺服器限制」一節。

Android 應用程式

您可以限制 API 金鑰只能用於特定的 Android 應用程式。您必須提供每個應用程式的套件名稱和 20 個位元組的 SHA-1 憑證指紋。

在要求中使用 API 金鑰時,您必須使用下列 HTTP 標頭指定套件名稱和憑證指紋:

  • X-Android-Package
  • X-Android-Cert

如要將 API 金鑰的使用限制到一或多個 Android 應用程式,請使用下列任一選項:

主控台

  1. 在 Google Cloud 控制台中,前往「憑證」頁面:

    前往「憑證」

  2. 按一下要設定限制的 API 金鑰名稱。

  3. 在「應用程式限制」部分中,選取「Android 應用程式」

  4. 針對每個要新增的 Android 應用程式,按一下「Add an item」並輸入套件名稱和 SHA-1 憑證指紋,然後按一下「Done」

  5. 按一下「儲存」儲存變更,然後返回 API 金鑰清單。

gcloud

  1. 取得要限制的金鑰 ID。

    ID 與顯示名稱或索引鍵字串不同。您可以使用 gcloud services api-keys list 指令列出專案中的金鑰,藉此取得 ID。

  2. 使用 gcloud services api-keys update 指令指定可使用 API 金鑰的 Android 應用程式。

    替換下列值:

    • KEY_ID:您要限制的鍵 ID。
    • SHA1_FINGERPRINTPACKAGE_NAME:可使用金鑰的 Android 應用程式應用程式資訊。

      您可以視需要新增任意數量的應用程式,並使用其他 --allowed-application 標記。

    gcloud services api-keys update KEY_ID \
    --allowed-application=sha1_fingerprint=SHA1_FINGERPRINT_1,package_name=PACKAGE_NAME_1 \
    --allowed-application=sha1_fingerprint=SHA1_FINGERPRINT_2,package_name=PACKAGE_NAME_2

Java

如要執行此範例,您必須安裝 google-cloud-apikeys 用戶端程式庫


import com.google.api.apikeys.v2.AndroidApplication;
import com.google.api.apikeys.v2.AndroidKeyRestrictions;
import com.google.api.apikeys.v2.ApiKeysClient;
import com.google.api.apikeys.v2.Key;
import com.google.api.apikeys.v2.Restrictions;
import com.google.api.apikeys.v2.UpdateKeyRequest;
import com.google.protobuf.FieldMask;
import java.io.IOException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

public class RestrictApiKeyAndroid {

  public static void main(String[] args)
      throws IOException, ExecutionException, InterruptedException, TimeoutException {
    // TODO(Developer): Before running this sample,
    //  1. Replace the variable(s) below.
    String projectId = "GOOGLE_CLOUD_PROJECT_ID";

    // ID of the key to restrict. This ID is auto-created during key creation.
    // This is different from the key string. To obtain the key_id,
    // you can also use the lookup api: client.lookupKey()
    String keyId = "key_id";

    restrictApiKeyAndroid(projectId, keyId);
  }

  // Restricts an API key based on android applications.
  // Specifies the Android application that can use the key.
  public static void restrictApiKeyAndroid(String projectId, String keyId)
      throws IOException, ExecutionException, InterruptedException, TimeoutException {
    // Initialize client that will be used to send requests. This client only needs to be created
    // once, and can be reused for multiple requests. After completing all of your requests, call
    // the `apiKeysClient.close()` method on the client to safely
    // clean up any remaining background resources.
    try (ApiKeysClient apiKeysClient = ApiKeysClient.create()) {

      // Restrict the API key usage by specifying the allowed android applications.
      Restrictions restrictions = Restrictions.newBuilder()
          .setAndroidKeyRestrictions(AndroidKeyRestrictions.newBuilder()
              .addAllowedApplications(AndroidApplication.newBuilder()
                  // Specify the android application's package name and SHA1 fingerprint.
                  .setPackageName("com.google.appname")
                  .setSha1Fingerprint("0873D391E987982FBBD30873D391E987982FBBD3")
                  .build())
              .build())
          .build();

      Key key = Key.newBuilder()
          .setName(String.format("projects/%s/locations/global/keys/%s", projectId, keyId))
          // Set the restriction(s).
          // For more information on API key restriction, see:
          // https://cloud.google.com/docs/authentication/api-keys
          .setRestrictions(restrictions)
          .build();

      // Initialize request and set arguments.
      UpdateKeyRequest updateKeyRequest = UpdateKeyRequest.newBuilder()
          .setKey(key)
          .setUpdateMask(FieldMask.newBuilder().addPaths("restrictions").build())
          .build();

      // Make the request and wait for the operation to complete.
      Key result = apiKeysClient.updateKeyAsync(updateKeyRequest).get(3, TimeUnit.MINUTES);

      // For authenticating with the API key, use the value in "result.getKeyString()".
      System.out.printf("Successfully updated the API key: %s", result.getName());
    }
  }
}

Python

如要執行這個範例,您必須安裝 API 金鑰用戶端程式庫


from google.cloud import api_keys_v2
from google.cloud.api_keys_v2 import Key


def restrict_api_key_android(project_id: str, key_id: str) -> Key:
    """
    Restricts an API key based on android applications.

    Specifies the Android application that can use the key.

    TODO(Developer): Replace the variables before running this sample.

    Args:
        project_id: Google Cloud project id.
        key_id: ID of the key to restrict. This ID is auto-created during key creation.
            This is different from the key string. To obtain the key_id,
            you can also use the lookup api: client.lookup_key()

    Returns:
        response: Returns the updated API Key.
    """

    # Create the API Keys client.
    client = api_keys_v2.ApiKeysClient()

    # Specify the android application's package name and SHA1 fingerprint.
    allowed_application = api_keys_v2.AndroidApplication()
    allowed_application.package_name = "com.google.appname"
    allowed_application.sha1_fingerprint = "0873D391E987982FBBD30873D391E987982FBBD3"

    # Restrict the API key usage by specifying the allowed applications.
    android_key_restriction = api_keys_v2.AndroidKeyRestrictions()
    android_key_restriction.allowed_applications = [allowed_application]

    # Set the restriction(s).
    # For more information on API key restriction, see:
    # https://cloud.google.com/docs/authentication/api-keys
    restrictions = api_keys_v2.Restrictions()
    restrictions.android_key_restrictions = android_key_restriction

    key = api_keys_v2.Key()
    key.name = f"projects/{project_id}/locations/global/keys/{key_id}"
    key.restrictions = restrictions

    # Initialize request and set arguments.
    request = api_keys_v2.UpdateKeyRequest()
    request.key = key
    request.update_mask = "restrictions"

    # Make the request and wait for the operation to complete.
    response = client.update_key(request=request).result()

    print(f"Successfully updated the API key: {response.name}")
    # Use response.key_string to authenticate.
    return response

REST

  1. 取得要限制的金鑰 ID。

    ID 與顯示名稱或索引鍵字串不同。您可以使用 keys.list 方法取得 ID。這個 ID 會列在回應的 uid 欄位中。

    PROJECT_ID 替換為您的 Google Cloud 專案 ID 或名稱。

    curl -X GET \
    -H "Authorization: Bearer $(gcloud auth print-access-token)" \
    "https://apikeys.googleapis.com/v2/projects/PROJECT_ID/locations/global/keys/"
  2. 使用 keys.patch 方法,指定可使用 API 金鑰的 Android 應用程式。

    這項要求會傳回長時間執行作業;您必須輪詢作業,才能瞭解作業完成的時間並取得作業狀態。

    替換下列值:

    • SHA1_FINGERPRINT_1PACKAGE_NAME_1:可使用金鑰的 Android 應用程式應用程式資訊。

      您可以視需要為任意數量的應用程式新增資訊,並使用逗號分隔 AndroidApplication 物件。您必須為要求提供所有應用程式;提供的應用程式會取代金鑰上任何現有的允許應用程式。

    • PROJECT_ID:您的 Google Cloud 專案 ID 或名稱。

    • KEY_ID:您要限制的鍵 ID。

    curl -X PATCH \
    -H "Authorization: Bearer $(gcloud auth print-access-token)" \
    -H "Content-Type: application/json; charset=utf-8" \
    --data '{
    "restrictions" : {
    "androidKeyRestrictions": {
      "allowedApplications": [
        {
          "sha1Fingerprint": "SHA1_FINGERPRINT_1",
          "packageName": "PACKAGE_NAME_1"
        },
     ]
    }
    }
    }' \
    "https://apikeys.googleapis.com/v2/projects/PROJECT_ID/locations/global/keys/KEY_ID?updateMask=restrictions"

如要進一步瞭解如何使用 REST API 將 Android 應用程式限制加入金鑰,請參閱 API 金鑰 API 說明文件中的「新增 Android 限制」一節。

iOS 應用程式

您可以提供各應用程式的軟體包 ID,限制 API 金鑰只能用於特定 iOS 應用程式。

在要求中使用 API 金鑰時,您必須使用 X-Ios-Bundle-Identifier HTTP 標頭指定軟體包 ID。

如要將 API 金鑰限制在一或多個 iOS 應用程式,請使用下列任一選項:

主控台

  1. 在 Google Cloud 控制台中,前往「Credentials」(憑證) 頁面:

    前往「憑證」

  2. 按一下要設定限制的 API 金鑰名稱。

  3. 在「應用程式限制」部分中選取「iOS 應用程式」

  4. 針對要新增的每個 iOS 應用程式,按一下「Add an item」(新增項目) 並輸入軟體包 ID,然後按一下「Done」(完成)

  5. 按一下「儲存」儲存變更,然後返回 API 金鑰清單。

gcloud

  1. 取得要限制的金鑰 ID。

    ID 與顯示名稱或索引鍵字串不同。您可以使用 gcloud services api-keys list 指令列出專案中的金鑰,藉此取得 ID。

  2. 使用 gcloud services api-keys update 方法指定可使用金鑰的 iOS 應用程式。

    替換下列值:

    • KEY_ID:您要限制的鍵 ID。
    • ALLOWED_BUNDLE_ID:您希望能夠使用此 API 金鑰的 iOS 應用程式軟體包 ID。

      您可以視需要新增任意數量的 bundle ID,並使用半形逗號分隔 ID。

    gcloud services api-keys update KEY_ID \
    --allowed-bundle-ids=ALLOWED_BUNDLE_ID_1,ALLOWED_BUNDLE_ID_2

Java

如要執行此範例,您必須安裝 google-cloud-apikeys 用戶端程式庫


import com.google.api.apikeys.v2.ApiKeysClient;
import com.google.api.apikeys.v2.IosKeyRestrictions;
import com.google.api.apikeys.v2.Key;
import com.google.api.apikeys.v2.Restrictions;
import com.google.api.apikeys.v2.UpdateKeyRequest;
import com.google.protobuf.FieldMask;
import java.io.IOException;
import java.util.Arrays;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

public class RestrictApiKeyIos {

  public static void main(String[] args)
      throws IOException, ExecutionException, InterruptedException, TimeoutException {
    // TODO(Developer): Before running this sample,
    //  1. Replace the variable(s) below.
    String projectId = "GOOGLE_CLOUD_PROJECT_ID";

    // ID of the key to restrict. This ID is auto-created during key creation.
    // This is different from the key string. To obtain the key_id,
    // you can also use the lookup api: client.lookupKey()
    String keyId = "key_id";

    restrictApiKeyIos(projectId, keyId);
  }

  // Restricts an API key. You can restrict usage of an API key to specific iOS apps
  // by providing the bundle ID of each app.
  public static void restrictApiKeyIos(String projectId, String keyId)
      throws IOException, ExecutionException, InterruptedException, TimeoutException {
    // Initialize client that will be used to send requests. This client only needs to be created
    // once, and can be reused for multiple requests. After completing all of your requests, call
    // the `apiKeysClient.close()` method on the client to safely
    // clean up any remaining background resources.
    try (ApiKeysClient apiKeysClient = ApiKeysClient.create()) {

      // Restrict the API key usage by specifying the bundle ID(s)
      // of iOS app(s) that can use the key.
      Restrictions restrictions = Restrictions.newBuilder()
          .setIosKeyRestrictions(IosKeyRestrictions.newBuilder()
              .addAllAllowedBundleIds(Arrays.asList("com.google.gmail", "com.google.drive"))
              .build())
          .build();

      Key key = Key.newBuilder()
          .setName(String.format("projects/%s/locations/global/keys/%s", projectId, keyId))
          // Set the restriction(s).
          // For more information on API key restriction, see:
          // https://cloud.google.com/docs/authentication/api-keys
          .setRestrictions(restrictions)
          .build();

      // Initialize request and set arguments.
      UpdateKeyRequest updateKeyRequest = UpdateKeyRequest.newBuilder()
          .setKey(key)
          .setUpdateMask(FieldMask.newBuilder().addPaths("restrictions").build())
          .build();

      // Make the request and wait for the operation to complete.
      Key result = apiKeysClient.updateKeyAsync(updateKeyRequest).get(3, TimeUnit.MINUTES);

      // For authenticating with the API key, use the value in "result.getKeyString()".
      System.out.printf("Successfully updated the API key: %s", result.getName());
    }
  }
}

Python

如要執行這個範例,您必須安裝 API 金鑰用戶端程式庫


from google.cloud import api_keys_v2
from google.cloud.api_keys_v2 import Key


def restrict_api_key_ios(project_id: str, key_id: str) -> Key:
    """
    Restricts an API key. You can restrict usage of an API key to specific iOS apps
    by providing the bundle ID of each app.

    TODO(Developer): Replace the variables before running this sample.

    Args:
        project_id: Google Cloud project id.
        key_id: ID of the key to restrict. This ID is auto-created during key creation.
            This is different from the key string. To obtain the key_id,
            you can also use the lookup api: client.lookup_key()

    Returns:
        response: Returns the updated API Key.
    """

    # Create the API Keys client.
    client = api_keys_v2.ApiKeysClient()

    # Restrict the API key usage by specifying the bundle ID(s) of iOS app(s) that can use the key.
    ios_key_restrictions = api_keys_v2.IosKeyRestrictions()
    ios_key_restrictions.allowed_bundle_ids = ["com.google.gmail", "com.google.drive"]

    # Set the API restriction.
    # For more information on API key restriction, see:
    # https://cloud.google.com/docs/authentication/api-keys
    restrictions = api_keys_v2.Restrictions()
    restrictions.ios_key_restrictions = ios_key_restrictions

    key = api_keys_v2.Key()
    key.name = f"projects/{project_id}/locations/global/keys/{key_id}"
    key.restrictions = restrictions

    # Initialize request and set arguments.
    request = api_keys_v2.UpdateKeyRequest()
    request.key = key
    request.update_mask = "restrictions"

    # Make the request and wait for the operation to complete.
    response = client.update_key(request=request).result()

    print(f"Successfully updated the API key: {response.name}")
    # Use response.key_string to authenticate.
    return response

REST

  1. 取得要限制的金鑰 ID。

    ID 與顯示名稱或索引鍵字串不同。您可以使用 keys.list 方法取得 ID。這個 ID 會列在回應的 uid 欄位中。

    PROJECT_ID 替換為您的 Google Cloud 專案 ID 或名稱。

    curl -X GET \
    -H "Authorization: Bearer $(gcloud auth print-access-token)" \
    "https://apikeys.googleapis.com/v2/projects/PROJECT_ID/locations/global/keys/"
  2. 使用 keys.patch 方法,指定可使用 API 金鑰的 iOS 應用程式。

    這項要求會傳回長時間執行作業;您必須輪詢作業,才能瞭解作業完成的時間並取得作業狀態。

    替換下列值:

    • ALLOWED_BUNDLE_ID:可使用金鑰的 iOS 應用程式組合 ID。

      您可以視需要新增多個應用程式的資訊,並使用半形逗號分隔套件 ID。您必須在要求中提供所有軟體包 ID;提供的軟體包 ID 會取代金鑰上任何現有的允許應用程式。

    • PROJECT_ID:您的 Google Cloud 專案 ID 或名稱。

    • KEY_ID:您要限制的鍵 ID。

    curl -X PATCH \
    -H "Authorization: Bearer $(gcloud auth print-access-token)" \
    -H "Content-Type: application/json; charset=utf-8" \
    --data '{
    "restrictions" : {
    "iosKeyRestrictions": {
      "allowedBundleIds": ["ALLOWED_BUNDLE_ID_1","ALLOWED_BUNDLE_ID_2"]
    }
    }
    }' \
    "https://apikeys.googleapis.com/v2/projects/PROJECT_ID/locations/global/keys/KEY_ID?updateMask=restrictions"

如要進一步瞭解如何使用 REST API 為金鑰新增 iOS 應用程式限制,請參閱 API 金鑰 API 說明文件中的「新增 iOS 限制」一節。

新增 API 限制

API 限制會指定可使用 API 金鑰呼叫的 API。

如要新增 API 限制,請使用下列其中一種做法:

主控台

  1. 在 Google Cloud 控制台中,前往「Credentials」(憑證) 頁面:

    前往「憑證」

  2. 按一下要設定限制的 API 金鑰名稱。

  3. 在「API 限制」專區中,按一下「限制金鑰」

  4. 選取 API 金鑰將用於存取的所有 API。

  5. 按一下「儲存」儲存變更,然後返回 API 金鑰清單。

gcloud

  1. 取得要限制的金鑰 ID。

    ID 與顯示名稱或索引鍵字串不同。您可以使用 gcloud services api-keys list 指令列出專案中的金鑰,藉此取得 ID。

  2. 使用 gcloud services api-keys update 指令指定哪些服務可使用 API 金鑰存取。

    替換下列值:

    • KEY_ID:您要限制的鍵 ID。
    • SERVICE_1SERVICE_2...:可透過金鑰存取的 API 服務名稱。

      您必須透過更新指令提供所有服務名稱;提供的服務名稱會取代金鑰上的任何現有服務。

    您可以在 API 資訊主頁上搜尋 API,找到服務名稱。服務名稱是字串,例如 bigquery.googleapis.com

    gcloud services api-keys update KEY_ID \
    --api-target=service=SERVICE_1 --api-target=service=SERVICE_2

Java

如要執行此範例,您必須安裝 google-cloud-apikeys 用戶端程式庫


import com.google.api.apikeys.v2.ApiKeysClient;
import com.google.api.apikeys.v2.ApiTarget;
import com.google.api.apikeys.v2.Key;
import com.google.api.apikeys.v2.Restrictions;
import com.google.api.apikeys.v2.UpdateKeyRequest;
import com.google.protobuf.FieldMask;
import java.io.IOException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

public class RestrictApiKeyApi {

  public static void main(String[] args)
      throws IOException, ExecutionException, InterruptedException, TimeoutException {
    // TODO(Developer): Before running this sample,
    //  1. Replace the variable(s) below.
    String projectId = "GOOGLE_CLOUD_PROJECT_ID";

    // ID of the key to restrict. This ID is auto-created during key creation.
    // This is different from the key string. To obtain the key_id,
    // you can also use the lookup api: client.lookupKey()
    String keyId = "key_id";

    restrictApiKeyApi(projectId, keyId);
  }

  // Restricts an API key. Restrictions specify which APIs can be called using the API key.
  public static void restrictApiKeyApi(String projectId, String keyId)
      throws IOException, ExecutionException, InterruptedException, TimeoutException {
    // Initialize client that will be used to send requests. This client only needs to be created
    // once, and can be reused for multiple requests. After completing all of your requests, call
    // the `apiKeysClient.close()` method on the client to safely
    // clean up any remaining background resources.
    try (ApiKeysClient apiKeysClient = ApiKeysClient.create()) {

      // Restrict the API key usage by specifying the target service and methods.
      // The API key can only be used to authenticate the specified methods in the service.
      Restrictions restrictions = Restrictions.newBuilder()
          .addApiTargets(ApiTarget.newBuilder()
              .setService("translate.googleapis.com")
              .addMethods("translate.googleapis.com.TranslateText")
              .build())
          .build();

      Key key = Key.newBuilder()
          .setName(String.format("projects/%s/locations/global/keys/%s", projectId, keyId))
          // Set the restriction(s).
          // For more information on API key restriction, see:
          // https://cloud.google.com/docs/authentication/api-keys
          .setRestrictions(restrictions)
          .build();

      // Initialize request and set arguments.
      UpdateKeyRequest updateKeyRequest = UpdateKeyRequest.newBuilder()
          .setKey(key)
          .setUpdateMask(FieldMask.newBuilder().addPaths("restrictions").build())
          .build();

      // Make the request and wait for the operation to complete.
      Key result = apiKeysClient.updateKeyAsync(updateKeyRequest).get(3, TimeUnit.MINUTES);

      // For authenticating with the API key, use the value in "result.getKeyString()".
      System.out.printf("Successfully updated the API key: %s", result.getName());
    }
  }
}

Python

如要執行這個範例,您必須安裝 API 金鑰用戶端程式庫


from google.cloud import api_keys_v2
from google.cloud.api_keys_v2 import Key


def restrict_api_key_api(project_id: str, key_id: str) -> Key:
    """
    Restricts an API key. Restrictions specify which APIs can be called using the API key.

    TODO(Developer): Replace the variables before running the sample.

    Args:
        project_id: Google Cloud project id.
        key_id: ID of the key to restrict. This ID is auto-created during key creation.
            This is different from the key string. To obtain the key_id,
            you can also use the lookup api: client.lookup_key()

    Returns:
        response: Returns the updated API Key.
    """

    # Create the API Keys client.
    client = api_keys_v2.ApiKeysClient()

    # Restrict the API key usage by specifying the target service and methods.
    # The API key can only be used to authenticate the specified methods in the service.
    api_target = api_keys_v2.ApiTarget()
    api_target.service = "translate.googleapis.com"
    api_target.methods = ["transate.googleapis.com.TranslateText"]

    # Set the API restriction(s).
    # For more information on API key restriction, see:
    # https://cloud.google.com/docs/authentication/api-keys
    restrictions = api_keys_v2.Restrictions()
    restrictions.api_targets = [api_target]

    key = api_keys_v2.Key()
    key.name = f"projects/{project_id}/locations/global/keys/{key_id}"
    key.restrictions = restrictions

    # Initialize request and set arguments.
    request = api_keys_v2.UpdateKeyRequest()
    request.key = key
    request.update_mask = "restrictions"

    # Make the request and wait for the operation to complete.
    response = client.update_key(request=request).result()

    print(f"Successfully updated the API key: {response.name}")
    # Use response.key_string to authenticate.
    return response

REST

  1. 取得要限制的金鑰 ID。

    ID 與顯示名稱或索引鍵字串不同。您可以使用 keys.list 方法取得 ID。這個 ID 會列在回應的 uid 欄位中。

    PROJECT_ID 替換為您的 Google Cloud 專案 ID 或名稱。

    curl -X GET \
    -H "Authorization: Bearer $(gcloud auth print-access-token)" \
    "https://apikeys.googleapis.com/v2/projects/PROJECT_ID/locations/global/keys/"
  2. 使用 keys.patch 方法,指定 API 金鑰可用於存取哪些服務。

    這項要求會傳回長時間執行作業;您必須輪詢作業,才能瞭解作業何時完成並取得作業狀態。

    替換下列值:

    • SERVICE_1SERVICE_2...:可透過金鑰存取的 API 服務名稱。

      您必須在要求中提供所有服務名稱;提供的服務名稱會取代金鑰上的任何現有服務。

      您可以在 API 資訊主頁上搜尋 API,找到服務名稱。服務名稱是字串,例如 bigquery.googleapis.com

    • PROJECT_ID:您的 Google Cloud 專案 ID 或名稱。

    • KEY_ID:您要限制的鍵 ID。

    curl -X PATCH \
    -H "Authorization: Bearer $(gcloud auth print-access-token)" \
    -H "Content-Type: application/json; charset=utf-8" \
    --data '{
    "restrictions" : {
    "apiTargets": [
      {
        "service": "SERVICE_1"
      },
      {
        "service" : "SERVICE_2"
      },
    ]
    }
    }' \
    "https://apikeys.googleapis.com/v2/projects/PROJECT_ID/locations/global/keys/KEY_ID?updateMask=restrictions"

如要進一步瞭解如何使用 REST API 為金鑰新增 API 限制,請參閱 API 金鑰 API 說明文件中的「新增 API 限制」一節。

從關鍵字串取得專案資訊

您可以根據字串判斷 API 金鑰與哪個 Google Cloud 專案相關聯。

KEY_STRING 替換為您需要專案資訊的鍵字串。

gcloud

您可以使用 gcloud services api-keys lookup 指令,從金鑰字串取得專案 ID。

 gcloud services api-keys lookup KEY_STRING
 

Java

如要執行此範例,您必須安裝 google-cloud-apikeys 用戶端程式庫


import com.google.api.apikeys.v2.ApiKeysClient;
import com.google.api.apikeys.v2.LookupKeyRequest;
import com.google.api.apikeys.v2.LookupKeyResponse;
import java.io.IOException;

public class LookupApiKey {

  public static void main(String[] args) throws IOException {
    // TODO(Developer): Before running this sample,
    //  1. Replace the variable(s) below.
    //  2. Set up ADC as described in https://cloud.google.com/docs/authentication/external/set-up-adc
    //  3. Make sure you have the necessary permission to view API keys.
    // API key string to retrieve the API key name.
    String apiKeyString = "API_KEY_STRING";

    lookupApiKey(apiKeyString);
  }

  // Retrieves name (full path) of an API key using the API key string.
  public static void lookupApiKey(String apiKeyString) throws IOException {
    // Initialize client that will be used to send requests. This client only needs to be created
    // once, and can be reused for multiple requests. After completing all of your requests, call
    // the `apiKeysClient.close()` method on the client to safely
    // clean up any remaining background resources.
    try (ApiKeysClient apiKeysClient = ApiKeysClient.create()) {

      // Initialize the lookup request and set the API key string.
      LookupKeyRequest lookupKeyRequest = LookupKeyRequest.newBuilder()
          .setKeyString(apiKeyString)
          .build();

      // Make the request and obtain the response.
      LookupKeyResponse response = apiKeysClient.lookupKey(lookupKeyRequest);

      System.out.printf("Successfully retrieved the API key name: %s", response.getName());
    }
  }
}

Python

如要執行這個範例,您必須安裝 API 金鑰用戶端程式庫


from google.cloud import api_keys_v2


def lookup_api_key(api_key_string: str) -> None:
    """
    Retrieves name (full path) of an API key using the API key string.

    TODO(Developer):
    1. Before running this sample,
      set up ADC as described in https://cloud.google.com/docs/authentication/external/set-up-adc
    2. Make sure you have the necessary permission to view API keys.

    Args:
        api_key_string: API key string to retrieve the API key name.
    """

    # Create the API Keys client.
    client = api_keys_v2.ApiKeysClient()

    # Initialize the lookup request and set the API key string.
    lookup_key_request = api_keys_v2.LookupKeyRequest(
        key_string=api_key_string,
        # Optionally, you can also set the etag (version).
        # etag=etag,
    )

    # Make the request and obtain the response.
    lookup_key_response = client.lookup_key(lookup_key_request)

    print(f"Successfully retrieved the API key name: {lookup_key_response.name}")

REST

您可以使用 lookupKey 方法,從鍵字串取得專案 ID。

curl -X GET \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "Content-Type: application/json; charset=utf-8" \
"https://apikeys.googleapis.com/v2/keys:lookupKey?keyString=KEY_STRING"

建立 API 金鑰的副本

如果您需要新的 API 金鑰,且限制與現有 API 金鑰相同,可以建立現有 API 金鑰的副本。這個作業會建立新的 API 金鑰,其中包含不重複的金鑰字串和 ID,以及現有 API 金鑰的限制。

複製作業僅適用於 Google Cloud 控制台。如要使用其他方法,請按照建立 API 金鑰的步驟操作,然後將相同的 API 金鑰限制套用至新產生的 API 金鑰。

  1. 在 Google Cloud 控制台中,前往「憑證」頁面:

    前往「憑證」

  2. 按一下要複製的 API 金鑰名稱。

    API 金鑰的詳細資料頁面隨即開啟。

  3. 按一下「建立副本」

  4. 輸入新 API 金鑰的名稱,並確認限制是否正確。

  5. 按一下 [建立]。

輪替 API 金鑰

定期輪替 API 金鑰,即可限制遭到入侵的 API 金鑰所造成的影響。

輪替 API 金鑰時,您會建立新金鑰,並為新金鑰設定與舊金鑰相同的限制,然後更新應用程式以便使用新金鑰。所有應用程式都更新後,您就可以刪除舊金鑰。

旋轉操作僅適用於 Google Cloud 控制台。如要使用其他方法,請按照建立 API 金鑰的步驟操作,然後將相同的 API 金鑰限制套用至新產生的 API 金鑰。更新應用程式以使用新金鑰後,請刪除舊金鑰。

  1. 在 Google Cloud 控制台中,前往「憑證」頁面:

    前往「憑證」

  2. 按一下要輪替的 API 金鑰名稱,開啟詳細資料頁面。

  3. 按一下「Rotate key」

  4. 輸入新 API 金鑰的名稱,並確認限制是否正確。

  5. 按一下 [建立]。

  6. 複製金鑰字串,並更新應用程式以使用新的字串。

  7. 更新所有應用程式以使用新金鑰後,請返回新金鑰的詳細資料頁面。在「先前的金鑰」部分,按一下「刪除先前的金鑰」即可刪除舊金鑰。

    如果發現自己過早刪除舊金鑰,可以取消刪除

可取消刪除 API 金鑰

如果不小心刪除 API 金鑰,可以在刪除後的 30 天內取消刪除 (還原) 該金鑰。30 天後,您就無法取消刪除 API 金鑰。

主控台

  1. 在 Google Cloud 控制台中,前往「憑證」頁面:

    前往「憑證」

  2. 按一下「還原已刪除的憑證」

  3. 找出要復原的已刪除 API 金鑰,然後按一下「還原」

    取消刪除 API 金鑰可能需要幾分鐘的時間才會生效。傳播後,未刪除的 API 金鑰會顯示在 API 金鑰清單中。

gcloud

  1. 取得要還原的金鑰 ID。

    ID 與顯示名稱或索引鍵字串不同。您可以使用 gcloud services api-keys list --show-deleted 指令列出專案中已刪除的金鑰,藉此取得 ID。

  2. 使用 gcloud services api-keys undelete 指令取消刪除 API 金鑰。

    gcloud services api-keys undelete KEY_ID

    替換下列值:

    • KEY_ID:要取消刪除的鍵 ID。

Java

如要執行此範例,您必須安裝 google-cloud-apikeys 用戶端程式庫

import com.google.api.apikeys.v2.ApiKeysClient;
import com.google.api.apikeys.v2.Key;
import com.google.api.apikeys.v2.UndeleteKeyRequest;
import java.io.IOException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

public class UndeleteApiKey {

  public static void main(String[] args)
      throws IOException, ExecutionException, InterruptedException, TimeoutException {
    // TODO(developer): Replace these variables before running the sample.
    // Project ID or project number of the Google Cloud project.
    String projectId = "YOUR_PROJECT_ID";
    // The API key id to undelete.
    String keyId = "YOUR_KEY_ID";

    undeleteApiKey(projectId, keyId);
  }

  // Undeletes an API key.
  public static void undeleteApiKey(String projectId, String keyId)
      throws IOException, ExecutionException, InterruptedException, TimeoutException {
    // Initialize client that will be used to send requests. This client only needs to be created
    // once, and can be reused for multiple requests.
    try (ApiKeysClient apiKeysClient = ApiKeysClient.create()) {

      // Initialize the undelete request and set the argument.
      UndeleteKeyRequest undeleteKeyRequest = UndeleteKeyRequest.newBuilder()
          .setName(String.format("projects/%s/locations/global/keys/%s", projectId, keyId))
          .build();

      // Make the request and wait for the operation to complete.
      Key undeletedKey = apiKeysClient.undeleteKeyAsync(undeleteKeyRequest)
          .get(3, TimeUnit.MINUTES);

      System.out.printf("Successfully undeleted the API key: %s", undeletedKey.getName());
    }
  }
}

REST

  1. 取得要還原的金鑰 ID。

    ID 與顯示名稱或索引鍵字串不同。您可以使用 keys.list 方法取得 ID,並將 showDeleted 查詢參數設為 true。金鑰 ID 會列在回應的 uid 欄位中。

    PROJECT_ID 替換為您的 Google Cloud 專案 ID 或名稱。

    curl -X GET \
    -H "Authorization: Bearer $(gcloud auth print-access-token)" \
    "https://apikeys.googleapis.com/v2/projects/PROJECT_ID/locations/global/keys?showDeleted=true"
  2. 使用 undelete 方法取消刪除 API 金鑰。

    curl -X POST \
    -H "Authorization: Bearer $(gcloud auth print-access-token)" \
    -H "Content-Type: application/json; charset=utf-8" \
    "https://apikeys.googleapis.com/v2/projects/PROJECT_ID/locations/global/keys/KEY_ID:undelete"

    這項要求會傳回長時間執行作業;您必須輪詢作業,才能瞭解作業完成的時間並取得作業狀態。

    替換下列值:

    • PROJECT_ID:您的 Google Cloud 專案 ID 或名稱。
    • KEY_ID:您要限制的鍵 ID。

判斷 API 金鑰類型

您可以檢查 API 金鑰,判斷該金鑰是否已繫結至服務帳戶。

主控台

  1. 在 Google Cloud 控制台中,前往「憑證」頁面:

    前往「憑證」

    如果 API 金鑰已繫結至服務帳戶,系統會顯示服務帳戶 ID。

gcloud

  1. 取得金鑰的 ID。

    ID 與顯示名稱或索引鍵字串不同。您可以使用 gcloud services api-keys list 指令列出專案中的金鑰,藉此取得 ID。

  2. 使用 gcloud services api-keys describe 指令說明 API 金鑰。

    gcloud services api-keys describe KEY_ID

    如果 API 金鑰已繫結至服務帳戶,系統會顯示 serviceAccountEmail 欄位。

輪詢長時間執行的作業

API Keys API 方法會使用長時間執行的作業。如果您使用 REST API 建立及管理 API 金鑰,系統會從初始方法要求傳回作業物件。您可以使用作業名稱輪詢長時間執行的作業。長時間執行要求完成後,輪詢作業會傳回長時間執行要求的資料。

如要輪詢長時間執行的 API Keys API 作業,請使用 operations.get 方法。

OPERATION_NAME 替換為長時間執行作業傳回的作業名稱。例如:operations/akmf.p7-358517206116-cd10a88a-7740-4403-a8fd-979f3bd7fe1c

curl -X GET \
    -H "Authorization: Bearer $(gcloud auth print-access-token)" \
    -H "Content-Type: application/json; charset=utf-8" \
    "https://apikeys.googleapis.com/v2/OPERATION_NAME"

API 金鑰限制

每個專案最多可建立 300 個 API 金鑰。這是系統限制,無法透過提高配額要求進行變更。如果需要更多 API 金鑰,您必須使用多個專案。

您最多可為 API 金鑰新增 1200 個應用程式限制

後續步驟