管理 API 密钥

本页面介绍了如何创建、修改和限制 API 密钥。

API 密钥简介

使用 API 密钥向 API 进行身份验证时,API 密钥不会标识主账号。API 密钥会将请求与 Google Cloud 项目关联,以进行结算和配额计算。如果没有主账号,请求就无法使用 Identity and Access Management (IAM) 检查调用方是否有权执行请求的操作。

API 密钥包含以下组成部分,可用于管理和使用密钥:

字符串
API 密钥字符串是加密的字符串,例如 AIzaSyDaGmWKa4JsXZ-HjGw7ISLn_3namBGewQe。当您使用 API 密钥进行身份验证时,始终是使用密钥的字符串。API 密钥没有关联的 JSON 文件。
ID
Google Cloud 管理工具使用 API 密钥 ID 来唯一标识密钥。密钥 ID 不能用于进行身份验证。您可以在 Google Cloud 控制台的密钥修改页面的网址中找到密钥 ID。您还可以使用 Google Cloud CLI 列出项目中的密钥来获取密钥 ID。
显示名称
显示名称是密钥的可选描述性名称,您可以在创建或更新密钥时设置该名称。

如需管理 API 密钥,您必须拥有项目的 API Keys Admin 角色 (roles/serviceusage.apiKeysAdmin)。

准备工作

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.

Java

如需在本地开发环境中使用本页面上的 Java 示例,请安装并初始化 gcloud CLI,然后使用您的用户凭据设置应用默认凭据。

  1. Install the Google Cloud CLI.
  2. To initialize the gcloud CLI, run the following command:

    gcloud init
  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.

如需了解详情,请参阅 Google Cloud 身份验证文档中的为本地开发环境设置身份验证

Python

如需在本地开发环境中使用本页面上的 Python 示例,请安装并初始化 gcloud CLI,然后使用您的用户凭据设置应用默认凭据。

  1. Install the Google Cloud CLI.
  2. To initialize the gcloud CLI, run the following command:

    gcloud init
  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.

如需了解详情,请参阅 Google Cloud 身份验证文档中的为本地开发环境设置身份验证

REST

如需在本地开发环境中使用本页面上的 REST API 示例,请使用您提供给 gcloud CLI 的凭据。

    Install the Google Cloud CLI, then initialize it by running the following command:

    gcloud init

如需了解详情,请参阅 Google Cloud 身份验证文档中的使用 REST 时进行身份验证

创建 API 密钥

如需创建 API 密钥,请使用以下选项之一:

控制台

  1. 在 Google Cloud 控制台中,进入凭据页面:

    进入“凭据”页面

  2. 选择创建凭据,然后从菜单中选择 API 密钥

    已创建的 API 密钥对话框会显示新创建的密钥的字符串。

gcloud

您可以使用 gcloud services api-keys create 命令创建 API 密钥。

DISPLAY_NAME 替换为密钥的描述性名称。

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

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"

如需详细了解如何使用 REST API 创建 API 密钥,请参阅 API Keys API 文档中的创建 API 密钥

请复制您的密钥字符串,并确保其安全。使用 API 密钥限制来限制密钥的使用方式。

应用 API 密钥限制

默认情况下,API 密钥不受限制。不受限制的密钥会带来安全方面的问题,因为任何人都可以随时随地使用此类密钥。对于生产应用,您应该同时设置应用限制API 限制

添加应用限制

应用限制用于指定哪些网站、IP 地址或应用可以使用 API 密钥。

您一次只能应用一种应用限制类型。根据您的应用类型选择限制类型:

选项 应用类型 备注
HTTP 引荐来源网址 Web 应用 指定可以使用密钥的网站。
IP 地址 由特定服务器调用的应用 指定可以使用密钥的服务器或 Cron 作业。
Android 应用 Android 应用 指定可以使用密钥的 Android 应用。
iOS 应用 iOS 应用 指定可以使用密钥的 iOS 软件包。

HTTP 引荐来源网址

如需限制可使用 API 密钥的网站,请添加一个或多个 HTTP 引荐来源网址限制。

您可以用通配符 (*) 来替换子网域或路径,但不能将通配符插入到网址的中间。例如,*.example.com 有效,并且接受以 .example.com 结尾的所有网站。但是,mysubdomain*.example.com 不是有效的限制。

HTTP 引荐来源网址限制中可以包含端口号。如果您添加了端口号,则系统只会匹配使用该端口的请求。如果您未指定端口号,则匹配来自任何端口号的请求。

您最多可以为 API 密钥添加 1200 个 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 引荐来源网址限制。

      您可以根据需要添加任意数量的限制;请使用英文逗号来分隔这些限制。您必须使用 update 命令来提供所有引荐来源网址限制;提供的引荐来源网址限制会替换密钥的任何现有引荐来源网址限制。

    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 Keys API 文档中的添加浏览器限制

IP 地址

您可以指定允许使用 API 密钥的调用方(例如 Web 服务器或 Cron 作业)的一个或多个 IP 地址。您可以采用以下任一格式指定 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 应用

您可以限制只有特定 Android 应用可以使用 API 密钥。您必须为每个应用提供软件包名称和 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 与显示名称或密钥字符串不同。您可以使用 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 Keys API 文档中的添加 Android 限制

iOS 应用

您可以通过提供每个应用的软件包 ID,将 API 密钥的使用仅限于特定 iOS 应用。

在请求中使用 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 与显示名称或密钥字符串不同。您可以使用 gcloud services api-keys list 命令列出项目中的密钥来获取此 ID。

  2. 使用 gcloud services api-keys update 方法指定可以使用该密钥的 iOS 应用。

    替换以下值:

    • KEY_ID:您要限制的密钥的 ID。
    • ALLOWED_BUNDLE_ID:可以使用此 API 密钥的 iOS 应用的软件包 ID。

      您可以根据需要添加任意数量的软件包 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 Keys API 文档中的添加 iOS 限制

添加 API 限制

API 限制用于指定可以使用 API 密钥调用哪些 API。

如需添加 API 限制,请使用以下选项之一:

控制台

  1. 在 Google Cloud 控制台中,进入凭据页面:

    进入“凭据”页面

  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 的服务名称。

      您必须使用 update 命令提供所有服务名称;提供的服务名称会替换密钥的任何现有服务。

    您可以在 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 Keys 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 密钥,可以在删除密钥后的 30 天内恢复删除的密钥。30 天后,您无法恢复删除的 API 密钥。

控制台

  1. 在 Google Cloud 控制台中,进入凭据页面:

    进入“凭据”页面

  2. 点击 Restore deleted credentials(恢复已删除的凭据)。

  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。

REST

  1. 获取要恢复的已删除密钥的 ID。

    此 ID 与显示名称或密钥字符串不同。您可以使用 keys.list 方法并将 showDeleted 查询参数设置为 true,以获取此 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?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 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 密钥,则必须使用多个项目。

后续步骤