查询可测试的权限

演示如何列出对资源有效的权限。

深入探索

如需查看包含此代码示例的详细文档,请参阅以下内容:

代码示例

C++

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

如需向 IAM 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证

namespace iam = ::google::cloud::iam_admin_v1;
[](std::string const& resource) {
  iam::IAMClient client(iam::MakeIAMConnection());
  google::iam::admin::v1::QueryTestablePermissionsRequest request;
  request.set_full_resource_name(resource);
  int count = 0;
  for (auto& permission : client.QueryTestablePermissions(request)) {
    if (!permission) throw std::move(permission).status();
    std::cout << "Permission successfully retrieved: " << permission->name()
              << "\n";
    ++count;
  }
  if (count == 0) {
    std::cout << "No testable permissions found in resource: " << resource
              << "\n";
  }
}

C#

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

如需向 IAM 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证


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

public partial class CustomRoles
{
    public static IList<Permission> QueryTestablePermissions(
        string fullResourceName)
    {
        var credential = GoogleCredential.GetApplicationDefault()
            .CreateScoped(IamService.Scope.CloudPlatform);
        var service = new IamService(new IamService.Initializer
        {
            HttpClientInitializer = credential
        });

        var request = new QueryTestablePermissionsRequest
        {
            FullResourceName = fullResourceName
        };
        var response = service.Permissions.QueryTestablePermissions(request)
            .Execute();
        foreach (var p in response.Permissions)
        {
            Console.WriteLine(p.Name);
        }
        return response.Permissions;
    }
}

Go

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

如需向 IAM 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证

import (
	"context"
	"fmt"
	"io"

	iam "google.golang.org/api/iam/v1"
)

// queryTestablePermissions lists testable permissions on a resource.
func queryTestablePermissions(w io.Writer, fullResourceName string) ([]*iam.Permission, error) {
	ctx := context.Background()
	service, err := iam.NewService(ctx)
	if err != nil {
		return nil, fmt.Errorf("iam.NewService: %w", err)
	}

	request := &iam.QueryTestablePermissionsRequest{
		FullResourceName: fullResourceName,
	}
	response, err := service.Permissions.QueryTestablePermissions(request).Do()
	if err != nil {
		return nil, fmt.Errorf("Permissions.QueryTestablePermissions: %w", err)
	}
	for _, p := range response.Permissions {
		fmt.Fprintf(w, "Found permissions: %v", p.Name)
	}
	return response.Permissions, nil
}

Java

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

如需向 IAM 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证


import com.google.cloud.iam.admin.v1.IAMClient;
import com.google.cloud.iam.admin.v1.IAMClient.QueryTestablePermissionsPagedResponse;
import com.google.iam.admin.v1.QueryTestablePermissionsRequest;
import java.io.IOException;

/** View available permissions in a project. */
public class QueryTestablePermissions {
  public static void main(String[] args) throws IOException {
    // TODO(developer): Replace the variable before running the sample.
    // Full resource names can take one of the following forms:
    // cloudresourcemanager.googleapis.com/projects/PROJECT_ID
    // cloudresourcemanager.googleapis.com/organizations/NUMERIC_ID
    String fullResourceName = "your-full-resource-name";

    queryTestablePermissions(fullResourceName);
  }

  public static void queryTestablePermissions(String fullResourceName) throws IOException {
    QueryTestablePermissionsRequest queryTestablePermissionsRequest =
        QueryTestablePermissionsRequest.newBuilder().setFullResourceName(fullResourceName).build();

    try (IAMClient iamClient = IAMClient.create()) {
      QueryTestablePermissionsPagedResponse queryTestablePermissionsPagedResponse =
          iamClient.queryTestablePermissions(queryTestablePermissionsRequest);
      queryTestablePermissionsPagedResponse
          .iterateAll()
          .forEach(permission -> System.out.println(permission.getName()));
    }
  }
}

Python

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

如需向 IAM 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证

from typing import List

from google.cloud import resourcemanager_v3
from google.iam.v1 import iam_policy_pb2, policy_pb2


def query_testable_permissions(
    project_id: str, permissions: List[str]
) -> policy_pb2.Policy:
    """
    Tests IAM permissions of the caller.

    project_id: ID or number of the Google Cloud project you want to use.
    """

    client = resourcemanager_v3.ProjectsClient()
    request = iam_policy_pb2.TestIamPermissionsRequest()
    request.resource = f"projects/{project_id}"
    request.permissions.extend(permissions)

    permissions_reponse = client.test_iam_permissions(request)
    print(permissions_reponse)
    return permissions_reponse.permissions

后续步骤

如需搜索和过滤其他 Google Cloud 产品的代码示例,请参阅 Google Cloud 示例浏览器