管理 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 是 aiplatform.googleapis.com

默认组织政策限制条件会阻止将密钥绑定到服务账号。如需更改此设置,请参阅启用将密钥绑定到服务账号功能

API 密钥组成部分

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

字符串
API 密钥字符串是加密的字符串,例如 AIzaSyDaGmWKa4JsXZ-HjGw7ISLn_3namBGewQe。当您使用 API 密钥访问 API 时,始终是使用密钥的字符串。API 密钥没有关联的 JSON 文件。
ID
Google Cloud 管理工具使用 API 密钥 ID 来唯一标识密钥。密钥 ID 无法用于访问 API。您可以在 Google Cloud 控制台的密钥修改页面的网址中找到密钥 ID。您还可以使用 Google Cloud CLI 列出项目中的密钥来获取密钥 ID。
显示名称
显示名称是密钥的可选描述性名称,您可以在创建或更新密钥时设置该名称。
已绑定的服务账号
绑定到服务账号的 API 密钥包含服务账号的邮箱。

准备工作

如需使用本页面上的示例,请完成以下任务。

设置身份验证

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

Console

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

gcloud

Install the Google Cloud CLI, and then sign in to the gcloud CLI with your federated identity. After signing in, initialize the Google Cloud CLI by running the following command:

gcloud init

C++

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

  1. Install the Google Cloud CLI.

  2. Configure the gcloud CLI to use your federated identity.

    For more information, see Sign in to the gcloud CLI with your federated identity.

  3. Create local authentication credentials for your user account:

    gcloud auth application-default login

    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. Configure the gcloud CLI to use your federated identity.

    For more information, see Sign in to the gcloud CLI with your federated identity.

  3. Create local authentication credentials for your user account:

    gcloud auth application-default login

    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

Python

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

  1. Install the Google Cloud CLI.

  2. Configure the gcloud CLI to use your federated identity.

    For more information, see Sign in to the gcloud CLI with your federated identity.

  3. Create local authentication credentials for your user account:

    gcloud auth application-default login

    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

REST

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

    Install the Google Cloud CLI, and then sign in to the gcloud CLI with your federated identity.

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

所需的角色

如需获得管理 API 密钥所需的权限,请让您的管理员为您授予项目的以下 IAM 角色:

  • API Keys Admin (roles/serviceusage.apiKeysAdmin)
  • 使用 Google Cloud 控制台将 API 密钥限制为特定 API:Service Usage Viewer (roles/serviceusage.serviceUsageViewer)

如需详细了解如何授予角色,请参阅管理对项目、文件夹和组织的访问权限

您也可以通过自定义角色或其他预定义角色来获取所需的权限。

启用将密钥绑定到服务账号功能

您需要先将 constraints/iam.managed.disableServiceAccountApiKeyCreation 组织政策限制条件设置为 false,然后才能将 API 密钥绑定到服务账号。更改组织政策需要关联的组织资源。不支持没有组织的项目。

如需更改政策限制条件,请按照以下说明操作。

控制台

  1. 在 Google Cloud 控制台中,转到组织政策页面。

    转到“组织政策”

  2. 切换到您要更改其政策的组织、文件夹或项目。

  3. 过滤条件框中,输入 Block service,然后点击过滤条件名称 Block service account API key bindings

  4. 点击管理政策

  5. 政策来源部分中,选择覆盖父资源的政策

  6. 点击添加规则,然后将强制执行设置为关闭

  7. 点击完成

  8. 可选:点击测试更改,以便深入了解所建议的政策可能会如何违反或破坏合规性。

  9. 点击设置政策

gcloud

  1. 创建一个名为 spec.yaml 的文件,其中包含以下内容:

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

    请提供以下值:

    • SCOPEorganizationsfoldersprojects

    • SCOPE_ID:组织政策适用的组织、文件夹或项目的 ID,具体取决于 SCOPE

  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./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"'}