访问权限控制

本文档介绍 Pub/Sub 中可用的访问权限控制选项。

概览

Pub/Sub 使用 Identity and Access Management (IAM) 进行访问权限控制。

在 Pub/Sub 中,既可以在项目级别配置访问权限控制,也可以在个别资源级别配置。例如:

  • 按主题或订阅授予访问权限,而不是授予对整个 Cloud 项目的访问权限。
  • 授予对有限功能的访问权限,例如只能向某主题发布消息,或者只能处理来自某订阅的消息,而不能删除该主题或订阅。
  • 向一组开发者授予对某项目中的所有 Pub/Sub 资源的访问权限。

如需详细了解 IAM 及其功能,请参阅 IAM 文档。尤其是授予、更改和撤消对资源的访问权限部分。

每种 Pub/Sub 方法都要求调用者拥有必要的权限。如需查看 Pub/Sub IAM 支持的权限和角色列表,请参阅下面的角色部分。

权限和角色

本部分汇总了 Pub/Sub IAM 支持的权限和角色。

所需权限

下表列出了调用者调用每个方法必须具备的权限:

方法 所需权限
projects.snapshots.create 针对所属 Cloud 项目的 pubsub.snapshots.create 权限以及针对源订阅的 pubsub.subscriptions.consume 权限。
projects.snapshots.delete 针对所请求快照的 pubsub.snapshots.delete 权限。
projects.snapshots.getIamPolicy 针对所请求快照的 pubsub.snapshots.getIamPolicy 权限。
projects.snapshots.list 针对所请求 Cloud 项目的 pubsub.snapshots.list 权限。
projects.snapshots.patch 针对所请求快照的 pubsub.snapshots.update 权限。
projects.snapshots.setIamPolicy 针对所请求快照的 pubsub.snapshots.setIamPolicy 权限。
projects.snapshots.testIamPermissions 无。
projects.subscriptions.acknowledge 针对所请求订阅的 pubsub.subscriptions.consume 权限。
projects.subscriptions.create 针对所属 Cloud 项目的 pubsub.subscriptions.create 权限以及针对所请求主题的 pubsub.topics.attachSubscription 权限。请注意,要在项目 A 中创建对项目 B 中主题 T 的订阅,必须同时对项目 A 和主题 T 授予适当的权限。在这种情况下,可以在项目 B 的审核日志中捕获用户身份信息。
projects.subscriptions.delete 针对所请求订阅的 pubsub.subscriptions.delete 权限。
projects.subscriptions.get 针对所请求订阅的 pubsub.subscriptions.get 权限。
projects.subscriptions.getIamPolicy 针对所请求订阅的 pubsub.subscriptions.getIamPolicy 权限。
projects.subscriptions.list 针对所请求 Cloud 项目的 pubsub.subscriptions.list 权限。
projects.subscriptions.modifyAckDeadline 针对所请求订阅的 pubsub.subscriptions.consume 权限。
projects.subscriptions.modifyPushConfig 针对所请求订阅的 pubsub.subscriptions.update 权限。
projects.subscriptions.patch 针对所请求订阅的 pubsub.subscriptions.update 权限。
projects.subscriptions.pull 针对所请求订阅的 pubsub.subscriptions.consume 权限。
projects.subscriptions.seek 针对所请求订阅的 pubsub.subscriptions.consume 权限,针对所请求快照的 pubsub.snapshots.seek 权限(如果有)。
projects.subscriptions.setIamPolicy 针对所请求订阅的 pubsub.subscriptions.setIamPolicy 权限。
projects.subscriptions.testIamPermissions 无。
projects.topics.create 针对所属 Cloud 项目的 pubsub.topics.create 权限。
projects.topics.delete 针对所请求主题的 pubsub.topics.delete 权限。
projects.topics.get 针对所请求主题的 pubsub.topics.get 权限。
projects.topics.getIamPolicy 针对所请求主题的 pubsub.topics.getIamPolicy 权限。
projects.topics.list 针对所请求 Cloud 项目的 pubsub.topics.list 权限。
projects.topics.patch 针对所请求主题的 pubsub.topics.update 权限。
projects.topics.publish 针对所请求主题的 pubsub.topics.publish 权限。
projects.topics.setIamPolicy 针对所请求主题的 pubsub.topics.setIamPolicy 权限。
projects.topics.subscriptions.list 针对所请求主题的 pubsub.topics.get 权限。
projects.topics.testIamPermissions 无。

角色

下表列出了 Pub/Sub IAM 角色及每个角色包含的所有权限的列表。请注意,每个权限适用于特定资源类型。

这些预配置的角色可以应对许多典型的使用场景。但是,您可能需要一个包含一组自定义权限的角色。例如,您可能希望创建一个角色,以允许用户在项目中创建订阅,但不允许他们删除或更新项目中的现有主题或订阅。在这种情况下,您可以创建符合自己需求的 IAM 自定义角色

角色 所含权限: 适用的资源类型:
roles/pubsub.publisher pubsub.topics.publish 主题
roles/pubsub.subscriber
pubsub.snapshots.seek 快照
pubsub.subscriptions.consume 订阅
pubsub.topics.attachSubscription 主题
roles/pubsub.viewer
roles/viewer
pubsub.snapshots.get 快照
pubsub.snapshots.list 项目
pubsub.subscriptions.get 订阅
pubsub.subscriptions.list 项目
pubsub.topics.get 主题
pubsub.topics.list 项目
resourcemanager.projects.get 项目
servicemanagement.projectSettings.get 项目
serviceusage.quotas.get 项目
serviceusage.services.get 项目
serviceusage.services.list 项目
roles/pubsub.editor
roles/editor
以上所有权限和下列权限:
pubsub.snapshots.create 项目
pubsub.snapshots.delete 快照
pubsub.snapshots.update 快照
pubsub.subscriptions.create 项目
pubsub.subscriptions.delete 订阅
pubsub.subscriptions.update 订阅
pubsub.topics.create 项目
pubsub.topics.delete 主题
pubsub.topics.update 主题
pubsub.topics.updateTag 主题
roles/pubsub.admin
roles/owner
以上所有权限和下列权限:
pubsub.snapshots.getIamPolicy 快照
pubsub.snapshots.setIamPolicy 快照
pubsub.subscriptions.getIamPolicy 订阅
pubsub.subscriptions.setIamPolicy 订阅
pubsub.topics.getIamPolicy 主题
pubsub.topics.setIamPolicy 主题

roles/owner、roles/editor、roles/viewer 角色也具有适用于其他 Google Cloud 服务的权限。

通过 Google Cloud Console 控制访问权限

您可以使用 GCP Console 来管理主题和项目的访问权限控制。

要在项目级别设置访问权限控制,请执行以下操作:

  1. 在 Cloud Console 中打开 IAM 页面
  2. 选择您的项目,然后点击继续
  3. 点击添加成员
  4. 输入先前未对其授予任何 IAM 角色的新成员的电子邮件地址。
  5. 从下拉菜单中选择一个角色。
  6. 点击“添加”。
  7. 验证该成员是否在您授予的角色下列出。

要为主题和订阅设置访问权限控制,请执行以下操作:

  1. 导航到控制台中的 Pub/Sub 主题页面
  2. 选择启用了 Pub/Sub 的项目。
  3. 选择主题或订阅。

    您一次可以针对多个主题设置权限。要针对某主题的订阅设置权限,请展开该主题并点击订阅,在其自身页面中打开。

  4. 点击权限。在显示的窗格中,执行以下操作:

    1. 输入一个或多个成员名称。
    2. 从下拉菜单中选择一个角色。
    3. 点击添加

通过 IAM API 控制访问权限

借助 Pub/Sub IAM API,您可以为项目中的个别主题和订阅设置和获取政策,以及测试用户对给定资源所具有的权限。与常规的 Pub/Sub 方法一样,您可以通过客户端库或 API Explorer 或者直接通过 HTTP 调用 IAM API 方法。

请注意,不能使用 Pub/Sub IAM API 在 Google Cloud 项目级别管理政策。

以下部分举例说明了如何设置和获取政策,以及如何测试调用者对给定资源具有什么权限。

获取政策

借助 getIamPolicy() 方法,您可以获取现有政策。此方法将返回包含与资源关联的政策的 JSON 对象。

以下一些示例代码演示了如何获取订阅政策

C#

在尝试此示例之前,请按照《快速入门:使用客户端库》中的 C# 设置说明进行操作。 如需了解详情,请参阅 Pub/Sub C# API 参考文档


using Google.Cloud.Iam.V1;
using Google.Cloud.PubSub.V1;

public class GetSubscriptionIamPolicySample
{
    public Policy GetSubscriptionIamPolicy(string projectId, string subscriptionId)
    {
        PublisherServiceApiClient publisher = PublisherServiceApiClient.Create();
        SubscriptionName subscriptionName = SubscriptionName.FromProjectSubscription(projectId, subscriptionId);
        Policy policy = publisher.GetIamPolicy(subscriptionName);
        return policy;
    }
}

gcloud

获取订阅政策:

gcloud pubsub subscriptions get-iam-policy \
   projects/${PROJECT}/subscriptions/${SUBSCRIPTION} \
   --format json

输出:

   {
     "etag": "BwUjMhCsNvY=",
     "bindings": [
       {
         "role": "roles/pubsub.admin",
         "members": [
           "user:user-1@gmail.com"
         ]
       },
       {
         "role": "roles/pubsub.editor",
         "members": [
           "serviceAccount:service-account-2@appspot.gserviceaccount.com",
           "user:user-3@gmail.com"
       }
     ]
   }

Go

在尝试此示例之前,请按照《快速入门:使用客户端库》中的 Go 设置说明进行操作。 如需了解详情,请参阅 Pub/Sub Go API 参考文档

import (
	"context"
	"fmt"
	"io"

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

func policy(w io.Writer, projectID, subID string) (*iam.Policy, error) {
	// projectID := "my-project-id"
	// subID := "my-sub"
	ctx := context.Background()
	client, err := pubsub.NewClient(ctx, projectID)
	if err != nil {
		return nil, fmt.Errorf("pubsub.NewClient: %v", err)
	}

	policy, err := client.Subscription(subID).IAM().Policy(ctx)
	if err != nil {
		return nil, fmt.Errorf("Subscription: %v", err)
	}
	for _, role := range policy.Roles() {
		fmt.Fprintf(w, "%q: %q\n", role, policy.Members(role))
	}
	return policy, nil
}

Java

在尝试此示例之前,请按照《快速入门:使用客户端库》中的 Java 设置说明进行操作。 如需了解详情,请参阅 Pub/Sub Java API 参考文档


import com.google.cloud.pubsub.v1.SubscriptionAdminClient;
import com.google.iam.v1.GetIamPolicyRequest;
import com.google.iam.v1.Policy;
import com.google.pubsub.v1.ProjectSubscriptionName;
import java.io.IOException;

public class GetSubscriptionPolicyExample {
  public static void main(String... args) throws Exception {
    // TODO(developer): Replace these variables before running the sample.
    String projectId = "your-project-id";
    String subscriptionId = "your-subscription-id";

    getSubscriptionPolicyExample(projectId, subscriptionId);
  }

  public static void getSubscriptionPolicyExample(String projectId, String subscriptionId)
      throws IOException {
    try (SubscriptionAdminClient subscriptionAdminClient = SubscriptionAdminClient.create()) {
      ProjectSubscriptionName subscriptionName =
          ProjectSubscriptionName.of(projectId, subscriptionId);
      GetIamPolicyRequest getIamPolicyRequest =
          GetIamPolicyRequest.newBuilder().setResource(subscriptionName.toString()).build();
      Policy policy = subscriptionAdminClient.getIamPolicy(getIamPolicyRequest);
      System.out.println("Subscription policy: " + policy);
    }
  }
}

Node.js

在尝试此示例之前,请按照《快速入门:使用客户端库》中的 Node.js 设置说明进行操作。如需了解详情,请参阅 Pub/Sub Node.js API 参考文档

/**
 * TODO(developer): Uncomment this variable before running the sample.
 */
// const subscriptionName = 'YOUR_SUBSCRIPTION_NAME';

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

// Creates a client; cache this for further use
const pubSubClient = new PubSub();

async function getSubscriptionPolicy() {
  // Retrieves the IAM policy for the subscription
  const [policy] = await pubSubClient
    .subscription(subscriptionName)
    .iam.getPolicy();

  console.log(`Policy for subscription: ${JSON.stringify(policy.bindings)}.`);
}

getSubscriptionPolicy().catch(console.error);

PHP

在尝试此示例之前,请按照《快速入门:使用客户端库》中的 PHP 设置说明进行操作。如需了解详情,请参阅 Pub/Sub PHP API 参考文档

use Google\Cloud\PubSub\PubSubClient;

/**
 * Prints the policy for a PubSub subscription.
 *
 * @param string $projectId  The Google project ID.
 * @param string $subscriptionName  The Pub/Sub subscription name.
 */
function get_subscription_policy($projectId, $subscriptionName)
{
    $pubsub = new PubSubClient([
        'projectId' => $projectId,
    ]);
    $subscription = $pubsub->subscription($subscriptionName);
    $policy = $subscription->iam()->policy();
    print_r($policy);
}

Python

在尝试此示例之前,请按照《快速入门:使用客户端库》中的 Python 设置说明进行操作。 如需了解详情,请参阅 Pub/Sub Python API 参考文档

from google.cloud import pubsub_v1

# TODO(developer)
# project_id = "your-project-id"
# subscription_id = "your-subscription-id"

client = pubsub_v1.SubscriberClient()
subscription_path = client.subscription_path(project, subscription_id)

policy = client.get_iam_policy(subscription_path)

print("Policy for subscription {}:".format(subscription_path))
for binding in policy.bindings:
    print("Role: {}, Members: {}".format(binding.role, binding.members))

client.close()

Ruby

在尝试此示例之前,请按照《快速入门:使用客户端库》中的 Ruby 设置说明进行操作。 如需了解详情,请参阅 Pub/Sub Ruby API 参考文档

# project_id        = "Your Google Cloud Project ID"
# subscription_name = "Your Pubsub subscription name"
require "google/cloud/pubsub"

pubsub = Google::Cloud::Pubsub.new project: project_id

subscription = pubsub.subscription subscription_name
policy       = subscription.policy

puts "Subscription policy:"
puts policy.roles

以下一些示例代码演示了如何获取主题政策

C#

在尝试此示例之前,请按照《快速入门:使用客户端库》中的 C# 设置说明进行操作。 如需了解详情,请参阅 Pub/Sub C# API 参考文档


using Google.Cloud.Iam.V1;
using Google.Cloud.PubSub.V1;

public class GetTopicIamPolicySample
{
    public Policy GetTopicIamPolicy(string projectId, string topicId)
    {
        PublisherServiceApiClient publisher = PublisherServiceApiClient.Create();
        TopicName topicName = TopicName.FromProjectTopic(projectId, topicId);
        Policy policy = publisher.GetIamPolicy(topicName);
        return policy;
    }
}

gcloud

获取主题政策

gcloud pubsub topics get-iam-policy \
    projects/${PROJECT}/topics/${TOPIC} \
    --format json

输出:

{
  "etag": "BwUjMhCsNvY=",
  "bindings": [
    {
      "role":" roles/pubsub.viewer",
      "members": [
        "user:user-1@gmail.com"
      ]
    }
  ]
}

Go

在尝试此示例之前,请按照《快速入门:使用客户端库》中的 Go 设置说明进行操作。 如需了解详情,请参阅 Pub/Sub Go API 参考文档

import (
	"context"
	"fmt"
	"io"

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

func policy(w io.Writer, projectID, topicID string) (*iam.Policy, error) {
	// projectID := "my-project-id"
	// topicID := "my-topic"
	ctx := context.Background()
	client, err := pubsub.NewClient(ctx, projectID)
	if err != nil {
		return nil, fmt.Errorf("pubsub.NewClient: %v", err)
	}

	policy, err := client.Topic(topicID).IAM().Policy(ctx)
	if err != nil {
		return nil, fmt.Errorf("Policy: %v", err)
	}
	for _, role := range policy.Roles() {
		fmt.Fprint(w, policy.Members(role))
	}
	return policy, nil
}

Java

在尝试此示例之前,请按照《快速入门:使用客户端库》中的 Java 设置说明进行操作。 如需了解详情,请参阅 Pub/Sub Java API 参考文档


import com.google.cloud.pubsub.v1.TopicAdminClient;
import com.google.iam.v1.GetIamPolicyRequest;
import com.google.iam.v1.Policy;
import com.google.pubsub.v1.TopicName;
import java.io.IOException;

public class GetTopicPolicyExample {
  public static void main(String... args) throws Exception {
    // TODO(developer): Replace these variables before running the sample.
    String projectId = "your-project-id";
    String topicId = "your-topic-id";

    getTopicPolicyExample(projectId, topicId);
  }

  public static void getTopicPolicyExample(String projectId, String topicId) throws IOException {
    try (TopicAdminClient topicAdminClient = TopicAdminClient.create()) {
      TopicName topicName = TopicName.of(projectId, topicId);
      GetIamPolicyRequest getIamPolicyRequest =
          GetIamPolicyRequest.newBuilder().setResource(topicName.toString()).build();
      Policy policy = topicAdminClient.getIamPolicy(getIamPolicyRequest);
      System.out.println("Topic policy: " + policy);
    }
  }
}

Node.js

在尝试此示例之前,请按照《快速入门:使用客户端库》中的 Node.js 设置说明进行操作。如需了解详情,请参阅 Pub/Sub Node.js API 参考文档

/**
 * TODO(developer): Uncomment this variable before running the sample.
 */
// const topicName = 'YOUR_TOPIC_NAME';

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

// Creates a client; cache this for further use
const pubSubClient = new PubSub();

async function getTopicPolicy() {
  // Retrieves the IAM policy for the topic
  const [policy] = await pubSubClient.topic(topicName).iam.getPolicy();
  console.log('Policy for topic: %j.', policy.bindings);
}

getTopicPolicy().catch(console.error);

PHP

在尝试此示例之前,请按照《快速入门:使用客户端库》中的 PHP 设置说明进行操作。如需了解详情,请参阅 Pub/Sub PHP API 参考文档

use Google\Cloud\PubSub\PubSubClient;

/**
 * Prints the policy for a Pub/Sub topic.
 *
 * @param string $projectId  The Google project ID.
 * @param string $topicName  The Pub/Sub topic name.
 */
function get_topic_policy($projectId, $topicName)
{
    $pubsub = new PubSubClient([
        'projectId' => $projectId,
    ]);
    $topic = $pubsub->topic($topicName);
    $policy = $topic->iam()->policy();
    print_r($policy);
}

Python

在尝试此示例之前,请按照《快速入门:使用客户端库》中的 Python 设置说明进行操作。 如需了解详情,请参阅 Pub/Sub Python API 参考文档

from google.cloud import pubsub_v1

# TODO(developer)
# project_id = "your-project-id"
# topic_id = "your-topic-id"

client = pubsub_v1.PublisherClient()
topic_path = client.topic_path(project, topic_id)

policy = client.get_iam_policy(topic_path)

print("Policy for topic {}:".format(topic_path))
for binding in policy.bindings:
    print("Role: {}, Members: {}".format(binding.role, binding.members))

Ruby

在尝试此示例之前,请按照《快速入门:使用客户端库》中的 Ruby 设置说明进行操作。 如需了解详情,请参阅 Pub/Sub Ruby API 参考文档

# project_id = "Your Google Cloud Project ID"
# topic_name = "Your Pubsub topic name"
require "google/cloud/pubsub"

pubsub = Google::Cloud::Pubsub.new project: project_id

topic  = pubsub.topic topic_name
policy = topic.policy

puts "Topic policy:"
puts policy.roles

设置政策

借助 setIamPolicy() 方法,您可以将政策附加到资源setIamPolicy() 方法接受一个 SetIamPolicyRequest,它包含要设置的政策和该政策要附加到的资源。该方法将返回生成的政策。

以下一些示例代码演示了如何为订阅设置政策

C#

在尝试此示例之前,请按照《快速入门:使用客户端库》中的 C# 设置说明进行操作。 如需了解详情,请参阅 Pub/Sub C# API 参考文档


using Google.Cloud.Iam.V1;
using Google.Cloud.PubSub.V1;

public class SetSubscriptionIamPolicySample
{
    public Policy SetSubscriptionIamPolicy(string projectId, string subscriptionId, string role, string member)
    {
        PublisherServiceApiClient publisher = PublisherServiceApiClient.Create();
        string roleToBeAddedToPolicy = $"roles/{role}";

        Policy policy = new Policy
        {
            Bindings = {
                new Binding
                {
                    Role = roleToBeAddedToPolicy,
                    Members = { member }
                }
            }
        };
        SetIamPolicyRequest request = new SetIamPolicyRequest
        {
            ResourceAsResourceName = SubscriptionName.FromProjectSubscription(projectId, subscriptionId),
            Policy = policy
        };
        Policy response = publisher.SetIamPolicy(request);
        return response;
    }
}

gcloud

1.保存订阅的政策。

gcloud pubsub subscriptions get-iam-policy \
   projects/${PROJECT}/subscriptions/${SUBSCRIPTION} \
   --format json > subscription_policy.json

2. 打开 subscription_policy.json 并通过向适当的成员提供适当的角色来更新绑定。如需详细了解如何使用 subscription_policy.json 文件,请参阅 IAM 文档中的政策

   {
     "etag": "BwUjMhCsNvY=",
     "bindings": [
       {
         "role": "roles/pubsub.admin",
         "members": [
           "user:user-1@gmail.com"
         ]
       },
       {
         "role": "roles/pubsub.editor",
         "members": [
           "serviceAccount:service-account-2@appspot.gserviceaccount.com"
       }
     ]
   }

3.应用新的订阅政策。

gcloud pubsub subscriptions set-iam-policy \
  projects/${PROJECT}/subscriptions/${SUBSCRIPTION} \
  subscription_policy.json

Go

在尝试此示例之前,请按照《快速入门:使用客户端库》中的 Go 设置说明进行操作。 如需了解详情,请参阅 Pub/Sub Go API 参考文档

import (
	"context"
	"fmt"

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

// addUsers adds all IAM users to a subscription.
func addUsers(projectID, subID string) error {
	// projectID := "my-project-id"
	// subID := "my-sub"
	ctx := context.Background()
	client, err := pubsub.NewClient(ctx, projectID)
	if err != nil {
		return fmt.Errorf("pubsub.NewClient: %v", err)
	}

	sub := client.Subscription(subID)
	policy, err := sub.IAM().Policy(ctx)
	if err != nil {
		return fmt.Errorf("Policy: %v", err)
	}
	// Other valid prefixes are "serviceAccount:", "user:"
	// See the documentation for more values.
	policy.Add(iam.AllUsers, iam.Viewer)
	policy.Add("group:cloud-logs@google.com", iam.Editor)
	if err := sub.IAM().SetPolicy(ctx, policy); err != nil {
		return fmt.Errorf("SetPolicy: %v", err)
	}
	// NOTE: It may be necessary to retry this operation if IAM policies are
	// being modified concurrently. SetPolicy will return an error if the policy
	// was modified since it was retrieved.
	return nil
}

Java

在尝试此示例之前,请按照《快速入门:使用客户端库》中的 Java 设置说明进行操作。 如需了解详情,请参阅 Pub/Sub Java API 参考文档


import com.google.cloud.pubsub.v1.SubscriptionAdminClient;
import com.google.iam.v1.Binding;
import com.google.iam.v1.GetIamPolicyRequest;
import com.google.iam.v1.Policy;
import com.google.iam.v1.SetIamPolicyRequest;
import com.google.pubsub.v1.ProjectSubscriptionName;
import java.io.IOException;

public class SetSubscriptionPolicyExample {
  public static void main(String... args) throws Exception {
    // TODO(developer): Replace these variables before running the sample.
    String projectId = "your-project-id";
    String subscriptionId = "your-subscription-id";

    setSubscriptionPolicyExample(projectId, subscriptionId);
  }

  public static void setSubscriptionPolicyExample(String projectId, String subscriptionId)
      throws IOException {
    try (SubscriptionAdminClient subscriptionAdminClient = SubscriptionAdminClient.create()) {
      ProjectSubscriptionName subscriptionName =
          ProjectSubscriptionName.of(projectId, subscriptionId);
      GetIamPolicyRequest getIamPolicyRequest =
          GetIamPolicyRequest.newBuilder().setResource(subscriptionName.toString()).build();
      Policy oldPolicy = subscriptionAdminClient.getIamPolicy(getIamPolicyRequest);

      // Create new role -> members binding
      Binding binding =
          Binding.newBuilder().setRole("roles/pubsub.editor").addMembers("allUsers").build();

      // Add new binding to updated policy
      Policy updatedPolicy = Policy.newBuilder(oldPolicy).addBindings(binding).build();

      SetIamPolicyRequest setIamPolicyRequest =
          SetIamPolicyRequest.newBuilder()
              .setResource(subscriptionName.toString())
              .setPolicy(updatedPolicy)
              .build();
      Policy newPolicy = subscriptionAdminClient.setIamPolicy(setIamPolicyRequest);
      System.out.println("New subscription policy: " + newPolicy);
    }
  }
}

Node.js

在尝试此示例之前,请按照《快速入门:使用客户端库》中的 Node.js 设置说明进行操作。如需了解详情,请参阅 Pub/Sub Node.js API 参考文档

/**
 * TODO(developer): Uncomment this variable before running the sample.
 */
// const subscriptionName = 'YOUR_SUBSCRIPTION_NAME';

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

// Creates a client; cache this for further use
const pubSubClient = new PubSub();

async function setSubscriptionPolicy() {
  // The new IAM policy
  const newPolicy = {
    bindings: [
      {
        // Add a group as editors
        role: 'roles/pubsub.editor',
        members: ['group:cloud-logs@google.com'],
      },
      {
        // Add all users as viewers
        role: 'roles/pubsub.viewer',
        members: ['allUsers'],
      },
    ],
  };

  // Updates the IAM policy for the subscription
  const [updatedPolicy] = await pubSubClient
    .subscription(subscriptionName)
    .iam.setPolicy(newPolicy);

  console.log('Updated policy for subscription: %j', updatedPolicy.bindings);
}

setSubscriptionPolicy().catch(console.error);

PHP

use Google\Cloud\PubSub\PubSubClient;

/**
 * Adds a user to the policy for a Pub/Sub subscription.
 *
 * @param string $projectId  The Google project ID.
 * @param string $subscriptionName  The Pub/Sub subscription name.
 * @param string $userEmail  The user email to add to the policy.
 */
function set_subscription_policy($projectId, $subscriptionName, $userEmail)
{
    $pubsub = new PubSubClient([
        'projectId' => $projectId,
    ]);
    $subscription = $pubsub->subscription($subscriptionName);
    $policy = $subscription->iam()->policy();
    $policy['bindings'][] = [
        'role' => 'roles/pubsub.subscriber',
        'members' => ['user:' . $userEmail]
    ];
    $subscription->iam()->setPolicy($policy);

    printf('User %s added to policy for %s' . PHP_EOL,
        $userEmail,
        $subscriptionName);
}

Python

在尝试此示例之前,请按照《快速入门:使用客户端库》中的 Python 设置说明进行操作。 如需了解详情,请参阅 Pub/Sub Python API 参考文档

from google.cloud import pubsub_v1

# TODO(developer)
# project_id = "your-project-id"
# subscription_id = "your-subscription-id"

client = pubsub_v1.SubscriberClient()
subscription_path = client.subscription_path(project, subscription_id)

policy = client.get_iam_policy(subscription_path)

# Add all users as viewers.
policy.bindings.add(role="roles/pubsub.viewer", members=["allUsers"])

# Add a group as an editor.
policy.bindings.add(role="roles/editor", members=["group:cloud-logs@google.com"])

# Set the policy
policy = client.set_iam_policy(subscription_path, policy)

print("IAM policy for subscription {} set: {}".format(subscription_id, policy))

client.close()

Ruby

在尝试此示例之前,请按照《快速入门:使用客户端库》中的 Ruby 设置说明进行操作。 如需了解详情,请参阅 Pub/Sub Ruby API 参考文档

# project_id        = "Your Google Cloud Project ID"
# subscription_name = "Your Pubsub subscription name"
require "google/cloud/pubsub"

pubsub = Google::Cloud::Pubsub.new project: project_id

subscription = pubsub.subscription subscription_name
subscription.policy do |policy|
  policy.add "roles/pubsub.subscriber",
             "serviceAccount:account-name@project-name.iam.gserviceaccount.com"
end

以下一些示例代码演示了如何为主题设置政策

C#

在尝试此示例之前,请按照《快速入门:使用客户端库》中的 C# 设置说明进行操作。 如需了解详情,请参阅 Pub/Sub C# API 参考文档


using Google.Cloud.Iam.V1;
using Google.Cloud.PubSub.V1;

public class SetTopicIamPolicySample
{
    public Policy SetTopicIamPolicy(string projectId, string topicId, string role, string member)
    {
        PublisherServiceApiClient publisher = PublisherServiceApiClient.Create();
        string roleToBeAddedToPolicy = $"roles/{role}";

        Policy policy = new Policy
        {
            Bindings = {
                new Binding
                {
                    Role = roleToBeAddedToPolicy,
                    Members = { member }
                }
            }
        };
        SetIamPolicyRequest request = new SetIamPolicyRequest
        {
            ResourceAsResourceName = TopicName.FromProjectTopic(projectId, topicId),
            Policy = policy
        };
        Policy response = publisher.SetIamPolicy(request);
        return response;
    }
}

gcloud

1.保存主题的政策。

gcloud pubsub topics get-iam-policy \
   projects/${PROJECT}/topics/${TOPIC} \
   --format json > topic_policy.json

2. 打开 topic_policy.json 并通过向适当的成员提供适当的角色来更新绑定。如需详细了解如何使用 subscription_policy.json 文件,请参阅 IAM 文档中的政策

   {
     "etag": "BwUjMhCsNvY=",
     "bindings": [
       {
         "role": "roles/pubsub.editor",
         "members": [
           "user:user-1@gmail.com",
           "user:user-2@gmail.com"
         ]
       }
     ]
   }

3.应用新的主题政策。

gcloud pubsub topics set-iam-policy  \
   projects/${PROJECT}topics/${TOPIC}     \
   topic_policy.json

Go

在尝试此示例之前,请按照《快速入门:使用客户端库》中的 Go 设置说明进行操作。 如需了解详情,请参阅 Pub/Sub Go API 参考文档

import (
	"context"
	"fmt"

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

func addUsers(projectID, topicID string) error {
	// projectID := "my-project-id"
	// topicID := "my-topic"
	ctx := context.Background()
	client, err := pubsub.NewClient(ctx, projectID)
	if err != nil {
		return fmt.Errorf("pubsub.NewClient: %v", err)
	}

	topic := client.Topic(topicID)
	policy, err := topic.IAM().Policy(ctx)
	if err != nil {
		return fmt.Errorf("Policy: %v", err)
	}
	// Other valid prefixes are "serviceAccount:", "user:"
	// See the documentation for more values.
	policy.Add(iam.AllUsers, iam.Viewer)
	policy.Add("group:cloud-logs@google.com", iam.Editor)
	if err := topic.IAM().SetPolicy(ctx, policy); err != nil {
		return fmt.Errorf("SetPolicy: %v", err)
	}
	// NOTE: It may be necessary to retry this operation if IAM policies are
	// being modified concurrently. SetPolicy will return an error if the policy
	// was modified since it was retrieved.
	return nil
}

Java

在尝试此示例之前,请按照《快速入门:使用客户端库》中的 Java 设置说明进行操作。 如需了解详情,请参阅 Pub/Sub Java API 参考文档


import com.google.cloud.pubsub.v1.TopicAdminClient;
import com.google.iam.v1.Binding;
import com.google.iam.v1.GetIamPolicyRequest;
import com.google.iam.v1.Policy;
import com.google.iam.v1.SetIamPolicyRequest;
import com.google.pubsub.v1.TopicName;
import java.io.IOException;

public class SetTopicPolicyExample {
  public static void main(String... args) throws Exception {
    // TODO(developer): Replace these variables before running the sample.
    String projectId = "your-project-id";
    String topicId = "your-topic-id";

    setTopicPolicyExample(projectId, topicId);
  }

  public static void setTopicPolicyExample(String projectId, String topicId) throws IOException {
    try (TopicAdminClient topicAdminClient = TopicAdminClient.create()) {
      TopicName topicName = TopicName.of(projectId, topicId);
      GetIamPolicyRequest getIamPolicyRequest =
          GetIamPolicyRequest.newBuilder().setResource(topicName.toString()).build();
      Policy oldPolicy = topicAdminClient.getIamPolicy(getIamPolicyRequest);

      // Create new role -> members binding
      Binding binding =
          Binding.newBuilder().setRole("roles/pubsub.editor").addMembers("allUsers").build();

      // Add new binding to updated policy
      Policy updatedPolicy = Policy.newBuilder(oldPolicy).addBindings(binding).build();

      SetIamPolicyRequest setIamPolicyRequest =
          SetIamPolicyRequest.newBuilder()
              .setResource(topicName.toString())
              .setPolicy(updatedPolicy)
              .build();
      Policy newPolicy = topicAdminClient.setIamPolicy(setIamPolicyRequest);
      System.out.println("New topic policy: " + newPolicy);
    }
  }
}

Node.js

在尝试此示例之前,请按照《快速入门:使用客户端库》中的 Node.js 设置说明进行操作。如需了解详情,请参阅 Pub/Sub Node.js API 参考文档

/**
 * TODO(developer): Uncomment this variable before running the sample.
 */
// const topicName = 'YOUR_TOPIC_NAME';

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

// Creates a client; cache this for further use
const pubSubClient = new PubSub();

async function setTopicPolicy() {
  // The new IAM policy
  const newPolicy = {
    bindings: [
      {
        // Add a group as editors
        role: 'roles/pubsub.editor',
        members: ['group:cloud-logs@google.com'],
      },
      {
        // Add all users as viewers
        role: 'roles/pubsub.viewer',
        members: ['allUsers'],
      },
    ],
  };

  // Updates the IAM policy for the topic
  const [updatedPolicy] = await pubSubClient
    .topic(topicName)
    .iam.setPolicy(newPolicy);
  console.log('Updated policy for topic: %j', updatedPolicy.bindings);
}

setTopicPolicy().catch(console.error);

PHP

use Google\Cloud\PubSub\PubSubClient;

/**
 * Adds a user to the policy for a Pub/Sub topic.
 *
 * @param string $projectId  The Google project ID.
 * @param string $topicName  The Pub/Sub topic name.
 * @param string $userEmail  The user email to add to the policy.
 */
function set_topic_policy($projectId, $topicName, $userEmail)
{
    $pubsub = new PubSubClient([
        'projectId' => $projectId,
    ]);
    $topic = $pubsub->topic($topicName);
    $policy = $topic->iam()->policy();
    $policy['bindings'][] = [
        'role' => 'roles/pubsub.publisher',
        'members' => ['user:' . $userEmail]
    ];
    $topic->iam()->setPolicy($policy);

    printf('User %s added to policy for %s' . PHP_EOL,
        $userEmail,
        $topicName);
}

Python

在尝试此示例之前,请按照《快速入门:使用客户端库》中的 Python 设置说明进行操作。 如需了解详情,请参阅 Pub/Sub Python API 参考文档

from google.cloud import pubsub_v1

# TODO(developer)
# project_id = "your-project-id"
# topic_id = "your-topic-id"

client = pubsub_v1.PublisherClient()
topic_path = client.topic_path(project, topic_id)

policy = client.get_iam_policy(topic_path)

# Add all users as viewers.
policy.bindings.add(role="roles/pubsub.viewer", members=["allUsers"])

# Add a group as a publisher.
policy.bindings.add(
    role="roles/pubsub.publisher", members=["group:cloud-logs@google.com"]
)

# Set the policy
policy = client.set_iam_policy(topic_path, policy)

print("IAM policy for topic {} set: {}".format(topic_id, policy))

Ruby

在尝试此示例之前,请按照《快速入门:使用客户端库》中的 Ruby 设置说明进行操作。 如需了解详情,请参阅 Pub/Sub Ruby API 参考文档

# project_id = "Your Google Cloud Project ID"
# topic_name = "Your Pubsub topic name"
require "google/cloud/pubsub"

pubsub = Google::Cloud::Pubsub.new project: project_id

topic = pubsub.topic topic_name
topic.policy do |policy|
  policy.add "roles/pubsub.publisher",
             "serviceAccount:account_name@project_name.iam.gserviceaccount.com"
end

测试权限

您可以使用 testIamPermissions() 方法来检查检查对于指定资源,调用者拥有指定权限中的哪些权限。该方法接受以参数形式传递的资源名称和一组权限,并返回调用者拥有的部分权限。

以下一些示例代码演示了如何测试订阅的权限

C#

在尝试此示例之前,请按照《快速入门:使用客户端库》中的 C# 设置说明进行操作。 如需了解详情,请参阅 Pub/Sub C# API 参考文档


using Google.Cloud.Iam.V1;
using Google.Cloud.PubSub.V1;

public class TestSubscriptionIamPermissionsSample
{
    public TestIamPermissionsResponse TestSubscriptionIamPermissionsResponse(string projectId, string subscriptionId)
    {
        TestIamPermissionsRequest request = new TestIamPermissionsRequest
        {
            ResourceAsResourceName = SubscriptionName.FromProjectSubscription(projectId, subscriptionId),
            Permissions = { "pubsub.subscriptions.get", "pubsub.subscriptions.update" }
        };
        PublisherServiceApiClient publisher = PublisherServiceApiClient.Create();
        TestIamPermissionsResponse response = publisher.TestIamPermissions(request);
        return response;
    }
}

gcloud

gcloud iam list-testable-permissions \
   https://pubsub.googleapis.com/v1/projects/${PROJECT}/subscriptions/${SUBSCRIPTION} \
   --format json

输出:

 [
    {
     "name": "pubsub.subscriptions.consume",
     "stage": "GA"
   },
   {
     "name": "pubsub.subscriptions.delete",
     "stage": "GA"
   },
   {
     "name": "pubsub.subscriptions.get",
     "stage": "GA"
   },
   {
     "name": "pubsub.subscriptions.getIamPolicy",
     "stage": "GA"
    },
   {
     "name": "pubsub.subscriptions.setIamPolicy",
     "stage": "GA"
   },
   {
     "name": "pubsub.subscriptions.update",
     "stage": "GA"
   }
 ]

Go

在尝试此示例之前,请按照《快速入门:使用客户端库》中的 Go 设置说明进行操作。 如需了解详情,请参阅 Pub/Sub Go API 参考文档

import (
	"context"
	"fmt"
	"io"

	"cloud.google.com/go/pubsub"
)

func testPermissions(w io.Writer, projectID, subID string) ([]string, error) {
	// projectID := "my-project-id"
	// subID := "my-sub"
	ctx := context.Background()
	client, err := pubsub.NewClient(ctx, projectID)
	if err != nil {
		return nil, fmt.Errorf("pubsub.NewClient: %v", err)
	}

	sub := client.Subscription(subID)
	perms, err := sub.IAM().TestPermissions(ctx, []string{
		"pubsub.subscriptions.consume",
		"pubsub.subscriptions.update",
	})
	if err != nil {
		return nil, fmt.Errorf("TestPermissions: %v", err)
	}
	for _, perm := range perms {
		fmt.Fprintf(w, "Allowed: %v\n", perm)
	}

Java

在尝试此示例之前,请按照《快速入门:使用客户端库》中的 Java 设置说明进行操作。 如需了解详情,请参阅 Pub/Sub Java API 参考文档


import com.google.cloud.pubsub.v1.SubscriptionAdminClient;
import com.google.iam.v1.TestIamPermissionsRequest;
import com.google.iam.v1.TestIamPermissionsResponse;
import com.google.pubsub.v1.ProjectSubscriptionName;
import java.io.IOException;
import java.util.LinkedList;
import java.util.List;

public class TestSubscriptionPermissionsExample {
  public static void main(String... args) throws Exception {
    // TODO(developer): Replace these variables before running the sample.
    String projectId = "your-project-id";
    String subscriptionId = "your-subscription-id";

    testSubscriptionPermissionsExample(projectId, subscriptionId);
  }

  public static void testSubscriptionPermissionsExample(String projectId, String subscriptionId)
      throws IOException {
    try (SubscriptionAdminClient subscriptionAdminClient = SubscriptionAdminClient.create()) {
      ProjectSubscriptionName subscriptionName =
          ProjectSubscriptionName.of(projectId, subscriptionId);

      List<String> permissions = new LinkedList<>();
      permissions.add("pubsub.subscriptions.consume");
      permissions.add("pubsub.subscriptions.update");

      TestIamPermissionsRequest testIamPermissionsRequest =
          TestIamPermissionsRequest.newBuilder()
              .setResource(subscriptionName.toString())
              .addAllPermissions(permissions)
              .build();

      TestIamPermissionsResponse testedPermissionsResponse =
          subscriptionAdminClient.testIamPermissions(testIamPermissionsRequest);

      System.out.println("Tested:\n" + testedPermissionsResponse);
    }
  }
}

Node.js

在尝试此示例之前,请按照《快速入门:使用客户端库》中的 Node.js 设置说明进行操作。如需了解详情,请参阅 Pub/Sub Node.js API 参考文档

/**
 * TODO(developer): Uncomment this variable before running the sample.
 */
// const subscriptionName = 'YOUR_SUBSCRIPTION_NAME';

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

// Creates a client; cache this for further use
const pubSubClient = new PubSub();

async function testSubscriptionPermissions() {
  const permissionsToTest = [
    'pubsub.subscriptions.consume',
    'pubsub.subscriptions.update',
  ];

  // Tests the IAM policy for the specified subscription
  const [permissions] = await pubSubClient
    .subscription(subscriptionName)
    .iam.testPermissions(permissionsToTest);

  console.log('Tested permissions for subscription: %j', permissions);
}

testSubscriptionPermissions().catch(console.error);

PHP

在尝试此示例之前,请按照《快速入门:使用客户端库》中的 PHP 设置说明进行操作。如需了解详情,请参阅 Pub/Sub PHP API 参考文档

use Google\Cloud\PubSub\PubSubClient;

/**
 * Prints the permissions of a subscription.
 *
 * @param string $projectId  The Google project ID.
 * @param string $subscriptionName  The Pub/Sub subscription name.
 */
function test_subscription_permissions($projectId, $subscriptionName)
{
    $pubsub = new PubSubClient([
        'projectId' => $projectId,
    ]);
    $subscription = $pubsub->subscription($subscriptionName);
    $permissions = $subscription->iam()->testPermissions([
        'pubsub.subscriptions.consume',
        'pubsub.subscriptions.update'
    ]);
    foreach ($permissions as $permission) {
        printf('Permission: %s' . PHP_EOL, $permission);
    }
}

Python

在尝试此示例之前,请按照《快速入门:使用客户端库》中的 Python 设置说明进行操作。 如需了解详情,请参阅 Pub/Sub Python API 参考文档

from google.cloud import pubsub_v1

# TODO(developer)
# project_id = "your-project-id"
# subscription_id = "your-subscription-id"

client = pubsub_v1.SubscriberClient()
subscription_path = client.subscription_path(project, subscription_id)

permissions_to_check = [
    "pubsub.subscriptions.consume",
    "pubsub.subscriptions.update",
]

allowed_permissions = client.test_iam_permissions(
    subscription_path, permissions_to_check
)

print(
    "Allowed permissions for subscription {}: {}".format(
        subscription_path, allowed_permissions
    )
)

client.close()

Ruby

在尝试此示例之前,请按照《快速入门:使用客户端库》中的 Ruby 设置说明进行操作。 如需了解详情,请参阅 Pub/Sub Ruby API 参考文档

# project_id        = "Your Google Cloud Project ID"
# subscription_name = "Your Pubsub subscription name"
require "google/cloud/pubsub"

pubsub = Google::Cloud::Pubsub.new project: project_id

subscription = pubsub.subscription subscription_name
permissions  = subscription.test_permissions "pubsub.subscriptions.consume",
                                             "pubsub.subscriptions.update"

puts "Permission to consume" if permissions.include? "pubsub.subscriptions.consume"
puts "Permission to update" if permissions.include? "pubsub.subscriptions.update"

以下一些示例代码演示了如何测试主题的权限

C#

在尝试此示例之前,请按照《快速入门:使用客户端库》中的 C# 设置说明进行操作。 如需了解详情,请参阅 Pub/Sub C# API 参考文档


using Google.Cloud.Iam.V1;
using Google.Cloud.PubSub.V1;

public class TestTopicIamPermissionsSample
{
    public TestIamPermissionsResponse TestTopicIamPermissions(string projectId, string topicId)
    {
        TestIamPermissionsRequest request = new TestIamPermissionsRequest
        {
            ResourceAsResourceName = TopicName.FromProjectTopic(projectId, topicId),
            Permissions = { "pubsub.topics.get", "pubsub.topics.update" }
        };
        PublisherServiceApiClient publisher = PublisherServiceApiClient.Create();
        TestIamPermissionsResponse response = publisher.TestIamPermissions(request);
        return response;
    }
}

gcloud

gcloud iam list-testable-permissions \
   https://pubsub.googleapis.com/v1/projects/${PROJECT}/topics/${TOPIC} \
   --format json

输出

 [
   {
     "name": "pubsub.topics.attachSubscription",
     "stage": "GA"
   },
   {
     "name": "pubsub.topics.delete",
     "stage": "GA"
   },
   {
     "name": "pubsub.topics.get",
     "stage": "GA"
   },
   {
     "name": "pubsub.topics.getIamPolicy",
     "stage": "GA"
   },
   {
     "name": "pubsub.topics.publish",
     "stage": "GA"
   },
   {
     "name": "pubsub.topics.setIamPolicy",
     "stage": "GA"
   },
   {
     "name": "pubsub.topics.update",
     "stage": "GA"
   }
 ]

Go

在尝试此示例之前,请按照《快速入门:使用客户端库》中的 Go 设置说明进行操作。 如需了解详情,请参阅 Pub/Sub Go API 参考文档

import (
	"context"
	"fmt"
	"io"

	"cloud.google.com/go/pubsub"
)

func testPermissions(w io.Writer, projectID, topicID string) ([]string, error) {
	// projectID := "my-project-id"
	// topicID := "my-topic"
	ctx := context.Background()
	client, err := pubsub.NewClient(ctx, projectID)
	if err != nil {
		return nil, fmt.Errorf("pubsub.NewClient: %v", err)
	}

	topic := client.Topic(topicID)
	perms, err := topic.IAM().TestPermissions(ctx, []string{
		"pubsub.topics.publish",
		"pubsub.topics.update",
	})
	if err != nil {
		return nil, fmt.Errorf("TestPermissions: %v", err)
	}
	for _, perm := range perms {
		fmt.Fprintf(w, "Allowed: %v\n", perm)
	}
	return perms, nil
}

Java

在尝试此示例之前,请按照《快速入门:使用客户端库》中的 Java 设置说明进行操作。 如需了解详情,请参阅 Pub/Sub Java API 参考文档


import com.google.cloud.pubsub.v1.TopicAdminClient;
import com.google.iam.v1.TestIamPermissionsRequest;
import com.google.iam.v1.TestIamPermissionsResponse;
import com.google.pubsub.v1.ProjectTopicName;
import java.io.IOException;
import java.util.LinkedList;
import java.util.List;

public class TestTopicPermissionsExample {

  public static void main(String... args) throws Exception {
    // TODO(developer): Replace these variables before running the sample.
    String projectId = "your-project-id";
    String topicId = "your-topic-id";

    testTopicPermissionsExample(projectId, topicId);
  }

  public static void testTopicPermissionsExample(String projectId, String topicId)
      throws IOException {
    try (TopicAdminClient topicAdminClient = TopicAdminClient.create()) {
      ProjectTopicName topicName = ProjectTopicName.of(projectId, topicId);

      List<String> permissions = new LinkedList<>();
      permissions.add("pubsub.topics.attachSubscription");
      permissions.add("pubsub.topics.publish");
      permissions.add("pubsub.topics.update");

      TestIamPermissionsRequest testIamPermissionsRequest =
          TestIamPermissionsRequest.newBuilder()
              .setResource(topicName.toString())
              .addAllPermissions(permissions)
              .build();

      TestIamPermissionsResponse testedPermissionsResponse =
          topicAdminClient.testIamPermissions(testIamPermissionsRequest);

      System.out.println("Tested:\n" + testedPermissionsResponse);
    }
  }
}

Node.js

在尝试此示例之前,请按照《快速入门:使用客户端库》中的 Node.js 设置说明进行操作。如需了解详情,请参阅 Pub/Sub Node.js API 参考文档

/**
 * TODO(developer): Uncomment this variable before running the sample.
 */
// const topicName = 'YOUR_TOPIC_NAME';

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

// Creates a client; cache this for further use
const pubSubClient = new PubSub();

async function testTopicPermissions() {
  const permissionsToTest = [
    'pubsub.topics.attachSubscription',
    'pubsub.topics.publish',
    'pubsub.topics.update',
  ];

  // Tests the IAM policy for the specified topic
  const [permissions] = await pubSubClient
    .topic(topicName)
    .iam.testPermissions(permissionsToTest);

  console.log('Tested permissions for topic: %j', permissions);
}

testTopicPermissions().catch(console.error);

PHP

在尝试此示例之前,请按照《快速入门:使用客户端库》中的 PHP 设置说明进行操作。如需了解详情,请参阅 Pub/Sub PHP API 参考文档

use Google\Cloud\PubSub\PubSubClient;

/**
 * Prints the permissions of a topic.
 *
 * @param string $projectId  The Google project ID.
 * @param string $topicName  The Pub/Sub topic name.
 */
function test_topic_permissions($projectId, $topicName)
{
    $pubsub = new PubSubClient([
        'projectId' => $projectId,
    ]);
    $topic = $pubsub->topic($topicName);
    $permissions = $topic->iam()->testPermissions([
        'pubsub.topics.attachSubscription',
        'pubsub.topics.publish',
        'pubsub.topics.update'
    ]);
    foreach ($permissions as $permission) {
        printf('Permission: %s' . PHP_EOL, $permission);
    }
}

Python

在尝试此示例之前,请按照《快速入门:使用客户端库》中的 Python 设置说明进行操作。 如需了解详情,请参阅 Pub/Sub Python API 参考文档

from google.cloud import pubsub_v1

# TODO(developer)
# project_id = "your-project-id"
# topic_id = "your-topic-id"

client = pubsub_v1.PublisherClient()
topic_path = client.topic_path(project, topic_id)

permissions_to_check = ["pubsub.topics.publish", "pubsub.topics.update"]

allowed_permissions = client.test_iam_permissions(topic_path, permissions_to_check)

print(
    "Allowed permissions for topic {}: {}".format(topic_path, allowed_permissions)
)

Ruby

在尝试此示例之前,请按照《快速入门:使用客户端库》中的 Ruby 设置说明进行操作。 如需了解详情,请参阅 Pub/Sub Ruby API 参考文档

# project_id = "Your Google Cloud Project ID"
# topic_name = "Your Pubsub topic name"
require "google/cloud/pubsub"

pubsub = Google::Cloud::Pubsub.new project: project_id

topic       = pubsub.topic topic_name
permissions = topic.test_permissions "pubsub.topics.attachSubscription",
                                     "pubsub.topics.publish", "pubsub.topics.update"

puts "Permission to attach subscription" if permissions.include? "pubsub.topics.attachSubscription"
puts "Permission to publish" if permissions.include? "pubsub.topics.publish"
puts "Permission to update" if permissions.include? "pubsub.topics.update"

示例使用场景:跨项目通信

Pub/Sub IAM 对于在跨项目通信中微调访问控制很有用。例如,假设 Cloud 项目 A 中的服务帐号想要将消息发布到 Cloud 项目 B 中的主题。为此,您可以在 Cloud 项目 B 中授予服务帐号“编辑”权限。但是,这种方法通常过于粗糙。您可以使用 IAM API 实现更精细的访问权限级别。

跨项目通信

例如,以下代码段使用 project-b 中的 setIamPolicy() 方法和一个准备好的 topic_policy.json 文件向 project-a 的服务帐号 foobar@project-a.iam.gserviceaccount.com 授予针对主题 projects/project-b/topics/topic-b 的 Publisher 角色:

gcloud pubsub topics set-iam-policy \
    projects/project-b/topics/topic-b \
    topic_policy.json
输出:
Updated IAM policy for topic topic-b.
bindings:
- members:
  - serviceAccount:foobar@project-a.iam.gserviceaccount.com
  role: roles/pubsub.publisher
etag: BwWGrQYX6R4=

部分可用性行为

授权检查取决于 IAM 子系统。为了持续对数据操作提供低延迟的响应(发布和消息处理),系统可能会依赖于缓存的 IAM 政策。如需了解更改何时生效,请参阅 IAM 文档