管理 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
管理工具會使用 API 金鑰 ID 準確識別金鑰。 Google Cloud 金鑰 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++

    如要在本機開發環境中使用本頁的 C++ 範例,請安裝並初始化 gcloud CLI,然後使用使用者憑證設定應用程式預設憑證。

    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.

    詳情請參閱 Google Cloud 驗證說明文件中的「 為本機開發環境設定 ADC」。

    Java

    如要在本機開發環境中使用本頁的 Java 範例,請安裝並初始化 gcloud CLI,然後使用使用者憑證設定應用程式預設憑證。

    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.

    詳情請參閱 Google Cloud 驗證說明文件中的「 為本機開發環境設定 ADC」。

    Python

    如要在本機開發環境中使用本頁的 Python 範例,請安裝並初始化 gcloud CLI,然後使用使用者憑證設定應用程式預設憑證。

    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.

    詳情請參閱 Google Cloud 驗證說明文件中的「 為本機開發環境設定 ADC」。

    REST

    如要在本機開發環境中使用本頁的 REST API 範例,請使用您提供給 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.

    詳情請參閱 Google Cloud 驗證說明文件中的「Authenticate for using REST」。

    必要的角色

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

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

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

    啟用金鑰與服務帳戶的繫結

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

    如要變更政策限制,請按照下列操作說明進行。

    主控台

    1. 前往 Google Cloud 控制台的「Organization policies」(組織政策) 頁面。

      前往「機構政策」

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

    3. 在「Filter」(篩選器) 方塊中輸入 Block service,然後按一下篩選器名稱「Block service account API key bindings」(封鎖服務帳戶 API 金鑰繫結)

    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 與顯示名稱或鍵字串不同,如要取得 ID,請使用 gcloud services api-keys list 指令列出專案中的金鑰。

    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 替換為您的專案 ID 或名稱。 Google Cloud

      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 與顯示名稱或鍵字串不同,如要取得 ID,請使用 gcloud services api-keys list 指令列出專案中的金鑰。

    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 替換為您的專案 ID 或名稱。 Google Cloud

      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 金鑰 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 應用程式,請按一下「新增項目」,然後輸入套件名稱和 SHA-1 憑證指紋,再按一下「完成」

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

    gcloud

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

      ID 與顯示名稱或鍵字串不同,如要取得 ID,請使用 gcloud services api-keys list 指令列出專案中的金鑰。

    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 替換為您的專案 ID 或名稱。 Google Cloud

      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,限制只有特定 iOS 應用程式可以使用某組 API 金鑰。

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

    如要限制 API 金鑰只能用於一或多個 iOS 應用程式,請使用下列其中一個選項:

    主控台

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

      前往「憑證」

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

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

    4. 如要新增 iOS 應用程式,請按一下「新增項目」並輸入軟體包 ID,然後按一下「完成」

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

    gcloud

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

      ID 與顯示名稱或鍵字串不同,如要取得 ID,請使用 gcloud services api-keys list 指令列出專案中的金鑰。

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

      替換下列值:

      • KEY_ID:要限制的金鑰 ID。
      • ALLOWED_BUNDLE_ID:您希望能夠使用這個 API 金鑰的 iOS 應用程式軟體包 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 替換為您的專案 ID 或名稱。 Google Cloud

      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 控制台的「憑證」頁面:

      前往「憑證」

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

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

    4. 選取 API 金鑰要存取的所有 API。

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

    gcloud

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

      ID 與顯示名稱或鍵字串不同,如要取得 ID,請使用 gcloud services api-keys list 指令列出專案中的金鑰。

    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 替換為您的專案 ID 或名稱。 Google Cloud

      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. 按一下「輪替金鑰」

    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 替換為您的專案 ID 或名稱。 Google Cloud

      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 與顯示名稱或鍵字串不同,如要取得 ID,請使用 gcloud services api-keys list 指令列出專案中的金鑰。

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

      gcloud services api-keys describe KEY_ID

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

    輪詢長時間執行的作業

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

    如要輪詢長期執行的 API 金鑰 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 項應用程式限制

    後續步驟