获取 IAM 成员

从 Cloud Storage 存储桶的 IAM 政策中获取成员。

深入探索

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

代码示例

C++

如需了解详情,请参阅 Cloud Storage C++ API 参考文档

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

namespace gcs = ::google::cloud::storage;
using ::google::cloud::StatusOr;
[](gcs::Client client, std::string const& bucket_name) {
  auto policy = client.GetNativeBucketIamPolicy(
      bucket_name, gcs::RequestedPolicyVersion(3));

  if (!policy) throw std::move(policy).status();
  std::cout << "The IAM policy for bucket " << bucket_name << " is "
            << *policy << "\n";
}

C#

如需了解详情,请参阅 Cloud Storage C# API 参考文档

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


using Google.Apis.Storage.v1.Data;
using Google.Cloud.Storage.V1;
using System;

public class ViewBucketIamMembersSample
{
    public Policy ViewBucketIamMembers(string bucketName = "your-unique-bucket-name")
    {
        var storage = StorageClient.Create();
        var policy = storage.GetBucketIamPolicy(bucketName, new GetBucketIamPolicyOptions
        {
            RequestedPolicyVersion = 3
        });

        foreach (var binding in policy.Bindings)
        {
            Console.WriteLine($"Role: {binding.Role}");
            Console.WriteLine("Members:");
            foreach (var member in binding.Members)
            {
                Console.WriteLine($"{member}");
            }
        }
        return policy;
    }
}

Go

如需了解详情,请参阅 Cloud Storage Go API 参考文档

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

import (
	"context"
	"fmt"
	"io"
	"time"

	"cloud.google.com/go/iam"
	"cloud.google.com/go/storage"
)

// getBucketPolicy gets the bucket IAM policy.
func getBucketPolicy(w io.Writer, bucketName string) (*iam.Policy3, error) {
	// bucketName := "bucket-name"
	ctx := context.Background()
	client, err := storage.NewClient(ctx)
	if err != nil {
		return nil, fmt.Errorf("storage.NewClient: %w", err)
	}
	defer client.Close()

	ctx, cancel := context.WithTimeout(ctx, time.Second*10)
	defer cancel()

	policy, err := client.Bucket(bucketName).IAM().V3().Policy(ctx)
	if err != nil {
		return nil, fmt.Errorf("Bucket(%q).IAM().V3().Policy: %w", bucketName, err)
	}
	for _, binding := range policy.Bindings {
		fmt.Fprintf(w, "%q: %q (condition: %v)\n", binding.Role, binding.Members, binding.Condition)
	}
	return policy, nil
}

Java

如需了解详情,请参阅 Cloud Storage Java API 参考文档

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

import com.google.cloud.Binding;
import com.google.cloud.Policy;
import com.google.cloud.storage.Storage;
import com.google.cloud.storage.StorageOptions;

public class ListBucketIamMembers {
  public static void listBucketIamMembers(String projectId, String bucketName) {
    // The ID of your GCP project
    // String projectId = "your-project-id";

    // The ID of your GCS bucket
    // String bucketName = "your-unique-bucket-name";

    // For more information please read:
    // https://cloud.google.com/storage/docs/access-control/iam
    Storage storage = StorageOptions.newBuilder().setProjectId(projectId).build().getService();

    Policy policy =
        storage.getIamPolicy(bucketName, Storage.BucketSourceOption.requestedPolicyVersion(3));

    // Print binding information
    for (Binding binding : policy.getBindingsList()) {
      System.out.printf("Role: %s Members: %s\n", binding.getRole(), binding.getMembers());

      // Print condition if one is set
      boolean bindingIsConditional = binding.getCondition() != null;
      if (bindingIsConditional) {
        System.out.printf("Condition Title: %s\n", binding.getCondition().getTitle());
        System.out.printf("Condition Description: %s\n", binding.getCondition().getDescription());
        System.out.printf("Condition Expression: %s\n", binding.getCondition().getExpression());
      }
    }
  }
}

Node.js

如需了解详情,请参阅 Cloud Storage Node.js API 参考文档

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

/**
 * TODO(developer): Uncomment the following lines before running the sample.
 */
// The ID of your GCS bucket
// const bucketName = 'your-unique-bucket-name';

// Imports the Google Cloud client library
const {Storage} = require('@google-cloud/storage');

// Creates a client
const storage = new Storage();

async function viewBucketIamMembers() {
  // For more information please read:
  // https://cloud.google.com/storage/docs/access-control/iam
  const results = await storage
    .bucket(bucketName)
    .iam.getPolicy({requestedPolicyVersion: 3});

  const bindings = results[0].bindings;

  console.log(`Bindings for bucket ${bucketName}:`);
  for (const binding of bindings) {
    console.log(`  Role: ${binding.role}`);
    console.log('  Members:');

    const members = binding.members;
    for (const member of members) {
      console.log(`    ${member}`);
    }

    const condition = binding.condition;
    if (condition) {
      console.log('  Condition:');
      console.log(`    Title: ${condition.title}`);
      console.log(`    Description: ${condition.description}`);
      console.log(`    Expression: ${condition.expression}`);
    }
  }
}

viewBucketIamMembers().catch(console.error);

PHP

如需了解详情,请参阅 Cloud Storage PHP API 参考文档

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

use Google\Cloud\Storage\StorageClient;

/**
 * View Bucket IAM members for a given Cloud Storage bucket.
 *
 * @param string $bucketName The name of your Cloud Storage bucket.
 *        (e.g. 'my-bucket')
 */
function view_bucket_iam_members(string $bucketName): void
{
    $storage = new StorageClient();
    $bucket = $storage->bucket($bucketName);

    $policy = $bucket->iam()->policy(['requestedPolicyVersion' => 3]);

    printf('Printing Bucket IAM members for Bucket: %s' . PHP_EOL, $bucketName);
    printf(PHP_EOL);

    foreach ($policy['bindings'] as $binding) {
        printf('Role: %s' . PHP_EOL, $binding['role']);
        printf('Members:' . PHP_EOL);
        foreach ($binding['members'] as $member) {
            printf('  %s' . PHP_EOL, $member);
        }

        if (isset($binding['condition'])) {
            $condition = $binding['condition'];
            printf('  with condition:' . PHP_EOL);
            printf('    Title: %s' . PHP_EOL, $condition['title']);
            printf('    Description: %s' . PHP_EOL, $condition['description']);
            printf('    Expression: %s' . PHP_EOL, $condition['expression']);
        }
        printf(PHP_EOL);
    }
}

Python

如需了解详情,请参阅 Cloud Storage Python API 参考文档

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

from google.cloud import storage


def view_bucket_iam_members(bucket_name):
    """View IAM Policy for a bucket"""
    # bucket_name = "your-bucket-name"

    storage_client = storage.Client()
    bucket = storage_client.bucket(bucket_name)

    policy = bucket.get_iam_policy(requested_policy_version=3)

    for binding in policy.bindings:
        print(f"Role: {binding['role']}, Members: {binding['members']}")

Ruby

如需了解详情,请参阅 Cloud Storage Ruby API 参考文档

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

def view_bucket_iam_members bucket_name:
  # The ID of your GCS bucket
  # bucket_name = "your-unique-bucket-name"

  require "google/cloud/storage"

  storage = Google::Cloud::Storage.new
  bucket = storage.bucket bucket_name

  policy = bucket.policy requested_policy_version: 3
  policy.bindings.each do |binding|
    puts "Role: #{binding.role}"
    puts "Members: #{binding.members}"

    # if a conditional binding exists print the condition.
    if binding.condition
      puts "Condition Title: #{binding.condition.title}"
      puts "Condition Description: #{binding.condition.description}"
      puts "Condition Expression: #{binding.condition.expression}"
    end
  end
end

后续步骤

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