测试自定义界面的权限

大多数 Google Cloud 资源都会公开 testIamPermissions() 方法,您可通过该方法以编程方式检查当前已通过身份验证的调用者是否已获得对相应资源的一项或多项特定的 IAM 权限。testIamPermissions() 方法将资源标识符和一组权限作为输入参数,并返回调用者可以使用的一组权限。

您可以使用 testIamPermissions() 方法来确定,用户是否应该有权限访问一个 Web 应用中的管理工具。例如,您可以使用此方法根据用户的权限决定是否显示某个 Google Cloud 资源的详细信息。

例如,如需确定当前通过身份验证的用户是否具有删除项目的权限,请通过提供项目 ID(例如 foo-project)和 resourcemanager.projects.delete 权限作为输入参数来调用 projects.testIamPermissions() 方法。如果调用者已获得 resourcemanager.projects.delete 权限,则响应正文将列出该权限。如果调用者没有此权限,则响应正文将不会列出任何权限。

testIamPermissions() 方法适用于第三方图形界面 (GUI),这些界面需要根据通过身份验证的用户有权查看的内容显示 Google Cloud 资源。例如,Google Cloud 控制台会在内部使用 testIamPermissions() 方法确定您在完成身份验证后可以看到哪些资源和功能。不同的用户通常会获得不同的权限,而 Google Cloud 控制台则会相应地隐藏或公开某些内容。

准备工作

  • 启用 Resource Manager API。

    启用 API

  • 设置身份验证。

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

    C++

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

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

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

      gcloud auth application-default login

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

    C#

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

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

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

      gcloud auth application-default login

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

    Java

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

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

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

      gcloud auth application-default login

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

    Python

    如需从本地开发环境使用本页面上的 Python 示例,请安装并初始化 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

所需的角色

测试权限不需要 IAM 角色。

如何测试权限

此示例展示了如何测试 Google Cloud 项目resourcemanager.projects.getresourcemanager.projects.delete 权限。如需测试其他 Google Cloud 资源的权限,请使用每个资源所公开的 testIamPermissions() 方法。例如,您可以测试 Cloud Storage 存储桶的 IAM 权限。

C++

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

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

namespace iam = ::google::cloud::iam_admin_v1;
[](std::string const& name, std::vector<std::string> const& permissions) {
  iam::IAMClient client(iam::MakeIAMConnection());
  auto response = client.TestIamPermissions(name, permissions);
  if (!response) throw std::move(response).status();
  std::cout << "Permissions successfully tested: " << response->DebugString()
            << "\n";
}

C#

如需向 Resource Manager 进行身份验证,请设置应用默认凭据。 如需了解更多信息,请参阅准备工作

如需了解如何安装和使用 Resource Manager 客户端库,请参阅 Resource Manager 客户端库

IAM 会测试您用来生成凭据的服务账号的权限。


using System;
using System.Collections.Generic;
using Google.Apis.Auth.OAuth2;
using Google.Apis.CloudResourceManager.v1;
using Google.Apis.CloudResourceManager.v1.Data;

public partial class AccessManager
{
    public static IList<String> TestIamPermissions(string projectId)
    {
        var credential = GoogleCredential.GetApplicationDefault()
            .CreateScoped(CloudResourceManagerService.Scope.CloudPlatform);
        var service = new CloudResourceManagerService(
            new CloudResourceManagerService.Initializer
            {
                HttpClientInitializer = credential
            });

        TestIamPermissionsRequest requestBody = new TestIamPermissionsRequest();
        var permissions = new List<string>() { "resourcemanager.projects.get", "resourcemanager.projects.delete" };
        requestBody.Permissions = new List<string>(permissions);
        var returnedPermissions = service.Projects.TestIamPermissions(requestBody, projectId).Execute().Permissions;

        return returnedPermissions;
    }
}

Java

如需向 Resource Manager 进行身份验证,请设置应用默认凭据。 如需了解更多信息,请参阅准备工作

如需了解如何安装和使用 Resource Manager 客户端库,请参阅 Resource Manager 客户端库

IAM 会测试您用来生成凭据的服务账号的权限。

import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
import com.google.api.client.json.gson.GsonFactory;
import com.google.api.services.cloudresourcemanager.v3.CloudResourceManager;
import com.google.api.services.cloudresourcemanager.v3.model.TestIamPermissionsRequest;
import com.google.api.services.cloudresourcemanager.v3.model.TestIamPermissionsResponse;
import com.google.api.services.iam.v1.IamScopes;
import com.google.auth.http.HttpCredentialsAdapter;
import com.google.auth.oauth2.GoogleCredentials;
import java.io.IOException;
import java.security.GeneralSecurityException;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

public class TestPermissions {

  // Tests if the caller has the listed permissions.
  public static void testPermissions(String projectId) {
    // projectId = "my-project-id"

    CloudResourceManager service = null;
    try {
      service = createCloudResourceManagerService();
    } catch (IOException | GeneralSecurityException e) {
      System.out.println("Unable to initialize service: \n" + e.toString());
      return;
    }

    List<String> permissionsList =
        Arrays.asList("resourcemanager.projects.get", "resourcemanager.projects.delete");

    TestIamPermissionsRequest requestBody =
        new TestIamPermissionsRequest().setPermissions(permissionsList);
    try {
      TestIamPermissionsResponse testIamPermissionsResponse =
          service.projects().testIamPermissions(projectId, requestBody).execute();

      System.out.println(
          "Of the permissions listed in the request, the caller has the following: "
              + testIamPermissionsResponse.getPermissions().toString());
    } catch (IOException e) {
      System.out.println("Unable to test permissions: \n" + e.toString());
    }
  }

  public static CloudResourceManager createCloudResourceManagerService()
      throws IOException, GeneralSecurityException {
    // 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));

    CloudResourceManager service =
        new CloudResourceManager.Builder(
                GoogleNetHttpTransport.newTrustedTransport(),
                GsonFactory.getDefaultInstance(),
                new HttpCredentialsAdapter(credential))
            .setApplicationName("service-accounts")
            .build();
    return service;
  }
}

Python

如需向 Resource Manager 进行身份验证,请设置应用默认凭据。 如需了解更多信息,请参阅准备工作

如需了解如何安装和使用 Resource Manager 客户端库,请参阅 Resource Manager 客户端库

IAM 会测试您用来生成凭据的服务账号的权限。

def test_permissions(project_id: str) -> dict:
    """Tests IAM permissions of the caller"""

    credentials = service_account.Credentials.from_service_account_file(
        filename=os.environ["GOOGLE_APPLICATION_CREDENTIALS"],
        scopes=["https://www.googleapis.com/auth/cloud-platform"],
    )
    service = googleapiclient.discovery.build(
        "cloudresourcemanager", "v1", credentials=credentials
    )

    permissions = {
        "permissions": [
            "resourcemanager.projects.get",
            "resourcemanager.projects.delete",
        ]
    }

    request = service.projects().testIamPermissions(
        resource=project_id, body=permissions
    )
    returnedPermissions = request.execute()
    print(returnedPermissions)
    return returnedPermissions

REST

在此示例中,用户具有 IAM 角色,因此可获取项目的相关信息,但不能删除项目。

Resource Manager API 的 projects.testIamPermissions 方法获取一个权限列表,并测试一个主账号拥有哪些权限。

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

  • PROJECT_ID:您的 Google Cloud 项目 ID。项目 ID 是字母数字字符串,例如 my-project

HTTP 方法和网址:

POST https://cloudresourcemanager.googleapis.com/v1/projects/PROJECT_ID:testIamPermissions

请求 JSON 正文:

{
  "permissions":  [
    "resourcemanager.projects.get",
    "resourcemanager.projects.delete"
  ]
}

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

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

{
  "permissions": [
    "resourcemanager.projects.get"
  ]
}

后续步骤

了解如何授予、更改和撤消主账号的访问权限