停用和启用服务账号密钥

本页面介绍了如何使用 Google Cloud 控制台、Google Cloud CLIIdentity and Access Management API 或某个 Google Cloud 客户端库来停用和启用服务账号密钥。

准备工作

  • 启用 IAM API。

    启用 API

  • 设置身份验证。

    选择标签页以了解您打算如何使用本页面上的示例:

    gcloud

    您可以从以下任一开发环境使用本页面上的 gcloud CLI 示例:

    • Cloud Shell:如需使用已设置 gcloud CLI 的在线终端,请激活 Cloud Shell。

      Cloud Shell 会话会在页面底部启动,并显示命令行提示符。该会话可能需要几秒钟来完成初始化。

    • 本地 shell:如需在本地开发环境中使用 gcloud CLI,请安装初始化 gcloud CLI。

    Java

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

    1. 安装 Google Cloud CLI。
    2. 如需初始化 gcloud CLI,请运行以下命令:

      gcloud init
    3. 为您的 Google 账号创建本地身份验证凭据:

      gcloud auth application-default login

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

    REST

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

      安装 Google Cloud CLI,然后通过运行以下命令初始化 Google Cloud CLI:

      gcloud init

  • 了解服务账号凭据

所需的角色

如需获得停用和启用服务账号密钥所需的权限,请让管理员向您授予项目或者您要管理其密钥的服务账号的 Service Account Key Admin (roles/iam.serviceAccountKeyAdmin) IAM 角色。如需详细了解如何授予角色,请参阅管理访问权限

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

如需了解详情,请参阅服务账号角色

IAM 基本角色还包含管理服务账号密钥的权限。您不应在生产环境中授予基本角色,但可以在开发或测试环境中授予这些角色。

停用服务账号密钥

停用服务账号密钥会导致您无法使用该密钥向 Google API 进行身份验证。您可以随时启用已停用的密钥

删除服务账号密钥之前,我们建议您先停用密钥,等到您确定不再需要该密钥时,即可将其删除。

您可以在 Google Cloud 控制台中查看已停用的密钥,但无法使用 Google Cloud 控制台停用密钥。请改用 gcloud CLI 或 REST API。

gcloud

执行 gcloud iam service-accounts keys disable 命令可停用服务账号密钥。

替换以下值:

  • KEY_ID:要停用的密钥的 ID。 如需查找密钥的 ID,请列出服务账号的所有密钥,找到要停用的密钥,然后复制其 ID。
  • SA_NAME:密钥所属服务账号的名称。
  • PROJECT_ID:您的 Google Cloud 项目 ID。
gcloud iam service-accounts keys disable KEY_ID \
    --iam-account=SA_NAME@PROJECT_ID.iam.gserviceaccount.com \
    --project=PROJECT_ID

输出如下:

Disabled key [KEY_ID] for service account
[SA_NAME@PROJECT_ID.iam.gserviceaccount.com]

Java

如需了解如何安装和使用 IAM 客户端库,请参阅 IAM 客户端库。如需了解详情,请参阅 IAM Java API 参考文档

如需向 IAM 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅准备工作


import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
import com.google.api.client.json.gson.GsonFactory;
import com.google.api.services.iam.v1.Iam;
import com.google.api.services.iam.v1.IamScopes;
import com.google.api.services.iam.v1.model.DisableServiceAccountKeyRequest;
import com.google.auth.http.HttpCredentialsAdapter;
import com.google.auth.oauth2.GoogleCredentials;
import java.io.IOException;
import java.security.GeneralSecurityException;
import java.util.Collections;

public class DisableServiceAccountKey {

  public static void main(String[] args) throws IOException {
    // TODO(Developer): Replace the below variables before running.
    String projectId = "gcloud-project-id";
    String serviceAccountName = "service-account-name";
    String serviceAccountKeyName = "service-account-key-name";

    disableServiceAccountKey(projectId, serviceAccountName, serviceAccountKeyName);
  }

  // Disables a service account key.
  public static void disableServiceAccountKey(String projectId, String serviceAccountName,
      String serviceAccountKeyName) {
    // Initialize the IAM service.
    Iam service = null;
    try {
      service = initService();
    } catch (IOException | GeneralSecurityException e) {
      System.out.println("Unable to initialize service: \n" + e);
      return;
    }

    // Construct the service account email.
    // You can modify the ".iam.gserviceaccount.com" to match the service account name in which
    // you want to disable the key.
    // See, https://cloud.google.com/iam/docs/creating-managing-service-account-keys?hl=en#disabling
    String serviceAccountEmail = serviceAccountName + "@" + projectId + ".iam.gserviceaccount.com";

    try {
      DisableServiceAccountKeyRequest
          disableServiceAccountKeyRequest = new DisableServiceAccountKeyRequest();
      // Use the IAM service to disable the service account key.
      service
          .projects()
          .serviceAccounts()
          .keys()
          .disable(String
              .format("projects/%s/serviceAccounts/%s/keys/%s", projectId, serviceAccountEmail,
                  serviceAccountKeyName), disableServiceAccountKeyRequest)
          .execute();

      System.out.println("Disabled service account key: " + serviceAccountKeyName);
    } catch (IOException e) {
      System.out.println("Failed to disable service account key: \n" + e);
    }
  }

  private static Iam initService() throws GeneralSecurityException, IOException {
    /* Use the Application Default Credentials strategy for authentication. For more info, see:
     https://cloud.google.com/docs/authentication/production#finding_credentials_automatically */
    GoogleCredentials credential =
        GoogleCredentials.getApplicationDefault()
            .createScoped(Collections.singleton(IamScopes.CLOUD_PLATFORM));

    // Initialize the IAM service, which can be used to send requests to the IAM API.
    return new Iam.Builder(
        GoogleNetHttpTransport.newTrustedTransport(),
        GsonFactory.getDefaultInstance(),
        new HttpCredentialsAdapter(credential))
        .setApplicationName("service-accounts")
        .build();
  }
}

REST

projects.serviceAccounts.keys.disable 方法可停用服务账号密钥。

在使用任何请求数据之前,请先进行以下替换:

  • PROJECT_ID:您的 Google Cloud 项目 ID。项目 ID 是字母数字字符串,例如 my-project
  • SA_NAME:您要停用其密钥的服务账号的名称。
  • KEY_ID:您要停用的密钥的 ID。 如需查找密钥的 ID,请列出服务账号的所有密钥,找到要停用的密钥,然后从 name 字段的末尾复制其 ID。密钥的 ID 是 keys/ 之后的所有内容。

HTTP 方法和网址:

POST https://iam.googleapis.com/v1/projects/PROJECT_ID/serviceAccounts/SA_NAME@PROJECT_ID.iam.gserviceaccount.com/keys/KEY_ID:disable

如需发送您的请求,请展开以下选项之一:

您应该收到类似以下内容的 JSON 响应:

{
}

启用服务账号密钥

停用服务账号密钥后,您可以随时启用该密钥,然后使用该密钥向 Google API 进行身份验证。

您不能使用 Google Cloud 控制台来启用服务账号密钥。请改用 gcloud CLI 或 REST API。

gcloud

执行 gcloud iam service-accounts keys enable 命令可启用服务账号密钥。

替换以下值:

  • KEY_ID:要启用的密钥的 ID。 如需查找密钥的 ID,请列出服务账号的所有密钥,找到要启用的密钥,然后复制其 ID。
  • SA_NAME:密钥所属服务账号的名称。
  • PROJECT_ID:您的 Google Cloud 项目 ID。
gcloud iam service-accounts keys enable KEY_ID \
    --iam-account=SA_NAME@PROJECT_ID.iam.gserviceaccount.com\
    --project=PROJECT_ID

输出如下:

Enabled key [KEY_ID] for service account
[SA_NAME@PROJECT_ID.iam.gserviceaccount.com]

Java

如需了解如何安装和使用 IAM 客户端库,请参阅 IAM 客户端库。如需了解详情,请参阅 IAM Java API 参考文档

如需向 IAM 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅准备工作


import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
import com.google.api.client.json.gson.GsonFactory;
import com.google.api.services.iam.v1.Iam;
import com.google.api.services.iam.v1.IamScopes;
import com.google.api.services.iam.v1.model.EnableServiceAccountKeyRequest;
import com.google.auth.http.HttpCredentialsAdapter;
import com.google.auth.oauth2.GoogleCredentials;
import java.io.IOException;
import java.security.GeneralSecurityException;
import java.util.Collections;

public class EnableServiceAccountKey {

  public static void main(String[] args) {
    // TODO(Developer): Replace the below variables before running.
    String projectId = "gcloud-project-id";
    String serviceAccountName = "service-account-name";
    String serviceAccountKeyName = "service-account-key-name";

    enableServiceAccountKey(projectId, serviceAccountName, serviceAccountKeyName);
  }

  // Enables a service account key.
  public static void enableServiceAccountKey(String projectId, String serviceAccountName,
      String serviceAccountKeyName) {
    // Initialize the IAM service.
    Iam service = null;
    try {
      service = initService();
    } catch (IOException | GeneralSecurityException e) {
      System.out.println("Unable to initialize service: \n" + e);
      return;
    }

    // Construct the service account email.
    // You can modify the ".iam.gserviceaccount.com" to match the service account name in which
    // you want to enable the key.
    // See, https://cloud.google.com/iam/docs/creating-managing-service-account-keys?hl=en#enabling
    String serviceAccountEmail = serviceAccountName + "@" + projectId + ".iam.gserviceaccount.com";

    try {
      EnableServiceAccountKeyRequest
          enableServiceAccountKeyRequest = new EnableServiceAccountKeyRequest();
      // Use the IAM service to enable the service account key.
      service
          .projects()
          .serviceAccounts()
          .keys()
          .enable(String
              .format("projects/%s/serviceAccounts/%s/keys/%s", projectId, serviceAccountEmail,
                  serviceAccountKeyName), enableServiceAccountKeyRequest)
          .execute();

      System.out.println("Enabled service account key: " + serviceAccountKeyName);
    } catch (IOException e) {
      System.out.println("Failed to enable service account key: \n" + e);
    }
  }

  private static Iam initService() throws GeneralSecurityException, IOException {
    /* Use the Application Default Credentials strategy for authentication. For more info, see:
     https://cloud.google.com/docs/authentication/production#finding_credentials_automatically */
    GoogleCredentials credential =
        GoogleCredentials.getApplicationDefault()
            .createScoped(Collections.singleton(IamScopes.CLOUD_PLATFORM));

    // Initialize the IAM service, which can be used to send requests to the IAM API.
    return new Iam.Builder(
        GoogleNetHttpTransport.newTrustedTransport(),
        GsonFactory.getDefaultInstance(),
        new HttpCredentialsAdapter(credential))
        .setApplicationName("service-accounts")
        .build();
  }
}

REST

projects.serviceAccounts.keys.enable 方法可启用服务账号密钥。

在使用任何请求数据之前,请先进行以下替换:

  • PROJECT_ID:您的 Google Cloud 项目 ID。项目 ID 是字母数字字符串,例如 my-project
  • SA_NAME:您要启用其密钥的服务账号的名称。
  • KEY_ID:您要启用的密钥的 ID。 如需查找密钥的 ID,请列出服务账号的所有密钥,找到要启用的密钥,然后从 name 字段的末尾复制其 ID。密钥的 ID 是 keys/ 之后的所有内容。

HTTP 方法和网址:

POST https://iam.googleapis.com/v1/projects/PROJECT_ID/serviceAccounts/SA_NAME@PROJECT_ID.iam.gserviceaccount.com/keys/KEY_ID:enable

如需发送您的请求,请展开以下选项之一:

您应该收到类似以下内容的 JSON 响应:

{
}

后续步骤

自行试用

如果您是 Google Cloud 新手,请创建一个账号来评估我们的产品在实际场景中的表现。新客户还可获享 $300 赠金,用于运行、测试和部署工作负载。

免费开始使用