使用 IAM 进行访问权限控制

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

概览

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

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

  • 按主题或订阅授予访问权限,而不是授予对整个 Cloud 项目的访问权限。

    如果您对某个主题或订阅只有查看权限,则无法使用 Google Cloud 控制台查看该主题或订阅。您可以改用 Google Cloud CLI。

  • 授予对有限功能的访问权限,例如只能向某主题发布消息,或者只能处理来自某订阅的消息,而不能删除该主题或订阅。

  • 向一组开发者授予对某项目中的所有 Pub/Sub 资源的访问权限。

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

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

权限和角色

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

所需权限

下表列出了调用每个方法所需的权限:

REST 方法 所需权限
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.detachSubscription 针对所请求主题的 pubsub.topics.detachSubscription 权限。
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 角色以及与每个角色关联的权限:

Role Permissions

(roles/pubsub.admin)

Provides full access to topics and subscriptions.

Lowest-level resources where you can grant this role:

  • Schema
  • Snapshot
  • Subscription
  • Topic

pubsub.*

  • pubsub.schemas.attach
  • pubsub.schemas.commit
  • pubsub.schemas.create
  • pubsub.schemas.delete
  • pubsub.schemas.get
  • pubsub.schemas.getIamPolicy
  • pubsub.schemas.list
  • pubsub.schemas.listRevisions
  • pubsub.schemas.rollback
  • pubsub.schemas.setIamPolicy
  • pubsub.schemas.validate
  • pubsub.snapshots.create
  • pubsub.snapshots.delete
  • pubsub.snapshots.get
  • pubsub.snapshots.getIamPolicy
  • pubsub.snapshots.list
  • pubsub.snapshots.seek
  • pubsub.snapshots.setIamPolicy
  • pubsub.snapshots.update
  • pubsub.subscriptions.consume
  • pubsub.subscriptions.create
  • pubsub.subscriptions.delete
  • pubsub.subscriptions.get
  • pubsub.subscriptions.getIamPolicy
  • pubsub.subscriptions.list
  • pubsub.subscriptions.setIamPolicy
  • pubsub.subscriptions.update
  • pubsub.topics.attachSubscription
  • pubsub.topics.create
  • pubsub.topics.delete
  • pubsub.topics.detachSubscription
  • pubsub.topics.get
  • pubsub.topics.getIamPolicy
  • pubsub.topics.list
  • pubsub.topics.publish
  • pubsub.topics.setIamPolicy
  • pubsub.topics.update
  • pubsub.topics.updateTag

resourcemanager.projects.get

serviceusage.quotas.get

serviceusage.services.get

serviceusage.services.list

(roles/pubsub.editor)

Provides access to modify topics and subscriptions, and access to publish and consume messages.

Lowest-level resources where you can grant this role:

  • Schema
  • Snapshot
  • Subscription
  • Topic

pubsub.schemas.attach

pubsub.schemas.commit

pubsub.schemas.create

pubsub.schemas.delete

pubsub.schemas.get

pubsub.schemas.list

pubsub.schemas.listRevisions

pubsub.schemas.rollback

pubsub.schemas.validate

pubsub.snapshots.create

pubsub.snapshots.delete

pubsub.snapshots.get

pubsub.snapshots.list

pubsub.snapshots.seek

pubsub.snapshots.update

pubsub.subscriptions.consume

pubsub.subscriptions.create

pubsub.subscriptions.delete

pubsub.subscriptions.get

pubsub.subscriptions.list

pubsub.subscriptions.update

pubsub.topics.attachSubscription

pubsub.topics.create

pubsub.topics.delete

pubsub.topics.detachSubscription

pubsub.topics.get

pubsub.topics.list

pubsub.topics.publish

pubsub.topics.update

pubsub.topics.updateTag

resourcemanager.projects.get

serviceusage.quotas.get

serviceusage.services.get

serviceusage.services.list

(roles/pubsub.publisher)

Provides access to publish messages to a topic.

Lowest-level resources where you can grant this role:

  • Topic

pubsub.topics.publish

(roles/pubsub.subscriber)

Provides access to consume messages from a subscription and to attach subscriptions to a topic.

Lowest-level resources where you can grant this role:

  • Snapshot
  • Subscription
  • Topic

pubsub.snapshots.seek

pubsub.subscriptions.consume

pubsub.topics.attachSubscription

(roles/pubsub.viewer)

Provides access to view topics and subscriptions.

Lowest-level resources where you can grant this role:

  • Schema
  • Snapshot
  • Subscription
  • Topic

pubsub.schemas.get

pubsub.schemas.list

pubsub.schemas.listRevisions

pubsub.schemas.validate

pubsub.snapshots.get

pubsub.snapshots.list

pubsub.subscriptions.get

pubsub.subscriptions.list

pubsub.topics.get

pubsub.topics.list

resourcemanager.projects.get

serviceusage.quotas.get

serviceusage.services.get

serviceusage.services.list

通过 Google Cloud 控制台控制访问权限

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

如需在项目级层设置访问权限控制,请按以下步骤操作:

  1. 在 Google Cloud 控制台中,前往 IAM 页面。

    转到 IAM

  2. 选择您的项目。

  3. 点击 Add

  4. 输入一个或多个主账号名称。

  5. 选择角色列表中,选择要授予的角色。

  6. 点击保存

  7. 验证该主账号是否拥有您授予的角色。

如需为主题和订阅设置访问权限控制,请按以下步骤操作:

  1. 在 Google Cloud 控制台中,前往 Pub/Sub 主题列表。

    前往“主题”页面

  2. 如有必要,请选择启用了 Pub/Sub 的项目。

  3. 执行以下步骤之一:

    • 如需为一个或多个主题设置角色,请选择相应主题。

    • 如需为附加到主题的订阅设置角色,请点击主题 ID。在主题详情页面中,点击订阅 ID。系统随即会显示订阅详情页面。

  4. 如果信息面板处于隐藏状态,请点击显示信息面板

  5. 权限标签页中,点击 添加主账号

  6. 输入一个或多个主账号名称。

  7. 选择角色列表中,选择要授予的角色。

  8. 点击保存

通过 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.IAMPolicyClient.GetIamPolicy(new GetIamPolicyRequest
        {
            ResourceAsResourceName = 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: %w", err)
	}
	defer client.Close()

	policy, err := client.Subscription(subID).IAM().Policy(ctx)
	if err != nil {
		return nil, fmt.Errorf("Subscription: %w", 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 subscriptionNameOrId = 'YOUR_SUBSCRIPTION_NAME_OR_ID';

// 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(subscriptionNameOrId) {
  // Retrieves the IAM policy for the subscription
  const [policy] = await pubSubClient
    .subscription(subscriptionNameOrId)
    .iam.getPolicy();

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

Node.js

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

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

// Imports the Google Cloud client library
import {PubSub, Policy} from '@google-cloud/pubsub';

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

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

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

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): Choose an existing subscription.
# project_id = "your-project-id"
# subscription_id = "your-subscription-id"

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

policy = client.get_iam_policy(request={"resource": 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 参考文档

# subscription_id = "your-subscription-id"

pubsub = Google::Cloud::Pubsub.new

subscription = pubsub.subscription subscription_id
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.IAMPolicyClient.GetIamPolicy(new GetIamPolicyRequest
        {
            ResourceAsResourceName = 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: %w", err)
	}
	defer client.Close()

	policy, err := client.Topic(topicID).IAM().Policy(ctx)
	if err != nil {
		return nil, fmt.Errorf("Policy: %w", 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 topicNameOrId = 'YOUR_TOPIC_NAME_OR_ID';

// 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(topicNameOrId) {
  // Retrieves the IAM policy for the topic
  const [policy] = await pubSubClient.topic(topicNameOrId).iam.getPolicy();
  console.log('Policy for topic: %j.', policy.bindings);
}

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): Choose an existing topic.
# project_id = "your-project-id"
# topic_id = "your-topic-id"

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

policy = client.get_iam_policy(request={"resource": 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 参考文档

# topic_id = "your-topic-id"

pubsub = Google::Cloud::Pubsub.new

topic  = pubsub.topic topic_id
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.IAMPolicyClient.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: %w", err)
	}
	defer client.Close()

	sub := client.Subscription(subID)
	policy, err := sub.IAM().Policy(ctx)
	if err != nil {
		return fmt.Errorf("err getting IAM Policy: %w", 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: %w", 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("domain:google.com")
              .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 subscriptionNameOrId = 'YOUR_SUBSCRIPTION_NAME_OR_ID';

// 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(subscriptionNameOrId) {
  // 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(subscriptionNameOrId)
    .iam.setPolicy(newPolicy);

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

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): Choose an existing subscription.
# project_id = "your-project-id"
# subscription_id = "your-subscription-id"

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

policy = client.get_iam_policy(request={"resource": subscription_path})

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

# 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(
    request={"resource": subscription_path, "policy": policy}
)

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

client.close()

Ruby

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

# subscription_id       = "your-subscription-id"
# role                  = "roles/pubsub.publisher"
# service_account_email = "serviceAccount:account_name@project_name.iam.gserviceaccount.com"

pubsub = Google::Cloud::Pubsub.new

subscription = pubsub.subscription subscription_id
subscription.policy do |policy|
  policy.add role, service_account_email
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.IAMPolicyClient.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: %w", err)
	}
	defer client.Close()

	topic := client.Topic(topicID)
	policy, err := topic.IAM().Policy(ctx)
	if err != nil {
		return fmt.Errorf("Policy: %w", 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: %w", 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("domain:google.com")
              .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 topicNameOrId = 'YOUR_TOPIC_NAME_OR_ID';

// 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(topicNameOrId) {
  // 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(topicNameOrId)
    .iam.setPolicy(newPolicy);
  console.log('Updated policy for topic: %j', updatedPolicy.bindings);
}

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): Choose an existing topic.
# project_id = "your-project-id"
# topic_id = "your-topic-id"

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

policy = client.get_iam_policy(request={"resource": topic_path})

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

# 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(request={"resource": topic_path, "policy": policy})

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

Ruby

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

# topic_id              = "your-topic-id"
# role                  = "roles/pubsub.publisher"
# service_account_email = "serviceAccount:account_name@project_name.iam.gserviceaccount.com"

pubsub = Google::Cloud::Pubsub.new

topic = pubsub.topic topic_id
topic.policy do |policy|
  policy.add role, service_account_email
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.IAMPolicyClient.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: %w", 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: %w", 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 subscriptionNameOrId = 'YOUR_SUBSCRIPTION_NAME_OR_ID';

// 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(subscriptionNameOrId) {
  const permissionsToTest = [
    'pubsub.subscriptions.consume',
    'pubsub.subscriptions.update',
  ];

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

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

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): Choose an existing subscription.
# project_id = "your-project-id"
# subscription_id = "your-subscription-id"

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

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

allowed_permissions = client.test_iam_permissions(
    request={"resource": subscription_path, "permissions": permissions_to_check}
)

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

client.close()

Ruby

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

# subscription_id = "your-subscription-id"

pubsub = Google::Cloud::Pubsub.new

subscription = pubsub.subscription subscription_id
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.IAMPolicyClient.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.detachSubscription",
     "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: %w", 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: %w", 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 topicNameOrId = 'YOUR_TOPIC_NAME_OR_ID';

// 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(topicNameOrId) {
  const permissionsToTest = [
    'pubsub.topics.attachSubscription',
    'pubsub.topics.publish',
    'pubsub.topics.update',
  ];

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

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

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): Choose an existing topic.
# project_id = "your-project-id"
# topic_id = "your-topic-id"

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

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

allowed_permissions = client.test_iam_permissions(
    request={"resource": topic_path, "permissions": permissions_to_check}
)

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

Ruby

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

# topic_id = "your-topic-id"

pubsub = Google::Cloud::Pubsub.new

topic       = pubsub.topic topic_id
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 中的主题。首先,在项目 A 中启用 Pub/Sub API。

其次,在 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 文档