管理 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 時,系統會將您的要求視為使用繫結的服務帳戶提出要求。

只有 aiplatform.googleapis.com 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. 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. 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. 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 的憑證。

    Install the Google Cloud CLI.

    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 角色:

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

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

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

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

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

主控台

  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 替換為您的 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 金鑰 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.