存取權控管

本文說明 Cloud Pub/Sub 中您可以使用的存取權控管選項。

  1. 總覽
  2. 權限與角色
    1. 所需權限
    2. 角色
  3. 透過 GCP 主控台的存取權控管
  4. 透過 Cloud Pub/Sub IAM API 的存取權控管
    1. 取得政策
    2. 設定政策
    3. 測試權限
  5. 用途範例:跨專案通訊
  6. 部分可用性行為

總覽

Cloud Pub/Sub 針對存取權控管使用 Google Cloud Identity and Access Management (Cloud IAM)。

在 Cloud Pub/Sub 中,可以在專案層級與個別資源層級設定存取權控管。例如:

  • 根據各主題或各訂閱項目,而不是針對整個 Cloud 專案授予存取權。
  • 授予功能有限制的存取權,例如僅將訊息發布到主題,或僅從訂閱項目中調用訊息,但不刪除主題或訂閱項目。
  • 向一組開發人員授予對專案內所有 Cloud Pub/Sub 資源的存取權。

如需 IAM 和其功能的相關詳細說明,請參閱開發人員專用的 Cloud Identity and Access Management 指南,其中以管理 IAM 政策一節最為重要。

每種 Cloud Pub/Sub 方法都需要呼叫方擁有必要權限。如需 Cloud Pub/Sub IAM 支援的權限與角色清單,請參閱下一節。

權限與角色

本節大致列出 Cloud Pub/Sub IAM 支援的權限與角色。

所需權限

下表列出了呼叫方呼叫每個方法時必須具備的權限:

方法 所需權限
projects.subscriptions.acknowledge 對要求訂閱項目的 pubsub.subscriptions.consume 權限。
projects.subscriptions.create 對內含 Cloud 專案的 pubsub.subscriptions.create 權限,以及對要求主題的 pubsub.topics.attachSubscription 權限。 請注意如要在專案 B 建立主題 T 的專案 A 訂閱,必須針對專案 A 及主題 T 授予適當權限。
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.pull 對要求訂閱項目的 pubsub.subscriptions.consume 權限。
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.publish 對要求主題的 pubsub.topics.publish 權限。
projects.topics.setIamPolicy 對要求主題的 pubsub.topics.setIamPolicy 權限。
projects.topics.testIamPermissions
projects.topics.subscriptions.list 對要求主題的 pubsub.topics.get 權限。

角色

下表列出 Cloud Pub/Sub Cloud IAM 角色,以及各角色具備的所有權限對應清單。請注意每個權限只適用於特定資源類型。

這些預先設定的角色可因應許多一般用途。不過您可能需要包含一組自訂權限的角色。例如您可能希望建立角色,讓使用者能在專案中建立訂閱,不必刪除或更新專案之中的現有主題或訂閱。在這類情況下,您可建立符合自己需求的 Cloud IAM 自訂角色

角色 具備的權限: 適用的資源類型:
roles/pubsub.publisher pubsub.topics.publish 主題
roles/pubsub.subscriber
pubsub.subscriptions.consume 訂閱項目
pubsub.topics.attachSubscription 主題
roles/pubsub.viewer
roles/viewer
pubsub.topics.list 專案
pubsub.topics.get 主題
pubsub.subscriptions.list 專案
pubsub.subscriptions.get 訂閱項目
roles/pubsub.editor
roles/editor
上述所有權限,以及下列權限:
pubsub.topics.create 專案
pubsub.topics.delete 主題
pubsub.topics.update 主題
pubsub.subscriptions.create 專案
pubsub.subscriptions.delete 訂閱項目
pubsub.subscriptions.update 訂閱項目
roles/pubsub.admin
roles/owner
上述所有權限,以及下列權限:
pubsub.topics.getIamPolicy 主題
pubsub.topics.setIamPolicy 主題
pubsub.subscriptions.getIamPolicy 訂閱項目
pubsub.subscriptions.setIamPolicy 訂閱項目
請注意,角色 roles/ownerroles/editorroles/viewer 也具備其他 Google Cloud Platform 服務的存取權限。

透過 GCP 主控台的存取權控管

您可以使用 GCP 主控台管理主題與專案的存取權控管。

如要在專案層級設定存取權控管:

  1. 在 Google Cloud Platform 主控台開啟 IAM 頁面
  2. 選取您的專案並按一下 [繼續]
  3. 按一下 [新增成員]
  4. 輸入您之前尚未授予任何 IAM 角色之新成員的電子郵件地址。
  5. 從下拉式選單中選取所需角色。
  6. 按一下 [Add] (新增)
  7. 確認成員列在您授予的角色下方。

如要設定主題與訂閱項目的存取權控管:

  1. 前往 GCP 主控台的 Pub/Sub 主題頁面,選取啟用 Cloud Pub/Sub 的專案。
  2. 選取您要設定權限的目標主題或訂閱項目。

    您一次可以設定多個主題的權限。如要設定主題訂閱項目的權限,請展開主題並按一下訂閱項目以在它自己的頁面中開啟。

  3. 按一下 [權限]。「權限」窗格會出現在畫面一側。
  4. 輸入一或多個成員名稱,從右側下拉式選單中選取角色,然後按一下 [新增]

透過 Cloud Pub/Sub IAM API 的存取權控管

Cloud Pub/Sub IAM API 可讓您設定及取得專案中個別主題與訂閱項目的政策,並測試使用者對指定資源的權限。與一般 Cloud Pub/Sub 方法一樣,您可以透過用戶端程式庫、API Explorer 或直接透過 HTTP 叫用 IAM 方法。

請注意,您無法使用 Cloud Pub/Sub IAM API 來管理 Cloud 專案層級的政策。

下列各節提供範例,說明如何設定及取得政策,以及如何測試呼叫方針對指定資源擁有的權限。

取得政策

getIamPolicy() 方法可讓您取得先前設定的政策。 這個方法會傳回包含與資源相關聯政策的 JSON 物件。

以下是取得訂閱政策的部分程式碼範例:

C#

在嘗試這個範例之前,請至 Cloud Pub/Sub 快速入門導覽課程:使用用戶端程式庫,按照 C# 設定說明進行操作。詳情請參閱 Cloud Pub/Sub C# API 參考說明文件

SubscriptionName subscriptionName = new SubscriptionName(projectId, subscriptionId);
Policy policy = publisher.GetIamPolicy(subscriptionName.ToString());
Console.WriteLine($"Subscription IAM Policy found for {subscriptionId}:");
Console.WriteLine(policy.Bindings);

GCLOUD 指令

儲存主題政策:

gcloud beta pubsub subscriptions get-iam-policy projects/{your_project}/subscriptions/ \
{your_topic} --format json > subscription_policy.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

在嘗試這個範例之前,請至 Cloud Pub/Sub 快速入門導覽課程:使用用戶端程式庫,按照 Go 設定說明進行操作。詳情請參閱 Cloud Pub/Sub Go API 參考說明文件

policy, err := c.Subscription(subName).IAM().Policy(ctx)
if err != nil {
	return nil, err
}
for _, role := range policy.Roles() {
	log.Printf("%q: %q", role, policy.Members(role))
}

Java

在嘗試這個範例之前,請至 Cloud Pub/Sub 快速入門導覽課程:使用用戶端程式庫,按照 Java 設定說明進行操作。詳情請參閱 Cloud Pub/Sub Java API 參考說明文件

try (SubscriptionAdminClient subscriptionAdminClient = SubscriptionAdminClient.create()) {
  ProjectSubscriptionName subscriptionName =
      ProjectSubscriptionName.of(projectId, subscriptionId);
  Policy policy = subscriptionAdminClient.getIamPolicy(subscriptionName.toString());
  if (policy == null) {
    // subscription was not found
  }
  return policy;
}

Node.js

在嘗試這個範例之前,請至 Cloud Pub/Sub 快速入門導覽課程:使用用戶端程式庫,按照 Node.js 設定說明進行操作。詳情請參閱 Cloud Pub/Sub Node.js API 參考說明文件

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

// Creates a client
const pubsub = new PubSub();

/**
 * TODO(developer): Uncomment the following line to run the sample.
 */
// const subscriptionName = 'my-sub';

// Retrieves the IAM policy for the subscription
const [policy] = await pubsub.subscription(subscriptionName).iam.getPolicy();
console.log(`Policy for subscription: ${JSON.stringify(policy.bindings)}.`);

PHP

在嘗試這個範例之前,請至 Cloud Pub/Sub 快速入門導覽課程:使用用戶端程式庫,按照 PHP 設定說明進行操作。詳情請參閱 Cloud 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

在嘗試這個範例之前,請至 Cloud Pub/Sub 快速入門導覽課程:使用用戶端程式庫,按照 Python 設定說明進行操作。詳情請參閱 Cloud Pub/Sub Python API 參考說明文件

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

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))

Ruby

在嘗試這個範例之前,請至 Cloud Pub/Sub 快速入門導覽課程:使用用戶端程式庫,按照 Ruby 設定說明進行操作。詳情請參閱 Cloud 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#

在嘗試這個範例之前,請至 Cloud Pub/Sub 快速入門導覽課程:使用用戶端程式庫,按照 C# 設定說明進行操作。詳情請參閱 Cloud Pub/Sub C# API 參考說明文件

TopicName topicName = new TopicName(projectId, topicId);
Policy policy = publisher.GetIamPolicy(topicName.ToString());
Console.WriteLine($"Topic IAM Policy found for {topicId}:");
Console.WriteLine(policy.Bindings);

GCLOUD 指令

取得主題政策:

gcloud beta pubsub topics get-iam-policy projects/{your_project}/topics/{your_topic} \
--format json > topic_policy.json

輸出:

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

Go

在嘗試這個範例之前,請至 Cloud Pub/Sub 快速入門導覽課程:使用用戶端程式庫,按照 Go 設定說明進行操作。詳情請參閱 Cloud Pub/Sub Go API 參考說明文件

policy, err := c.Topic(topicName).IAM().Policy(ctx)
if err != nil {
	return nil, err
}
for _, role := range policy.Roles() {
	log.Print(policy.Members(role))
}

Java

在嘗試這個範例之前,請至 Cloud Pub/Sub 快速入門導覽課程:使用用戶端程式庫,按照 Java 設定說明進行操作。詳情請參閱 Cloud Pub/Sub Java API 參考說明文件

try (TopicAdminClient topicAdminClient = TopicAdminClient.create()) {
  ProjectTopicName topicName = ProjectTopicName.of(projectId, topicId);
  Policy policy = topicAdminClient.getIamPolicy(topicName.toString());
  if (policy == null) {
    // topic iam policy was not found
  }
  return policy;
}

Node.js

在嘗試這個範例之前,請至 Cloud Pub/Sub 快速入門導覽課程:使用用戶端程式庫,按照 Node.js 設定說明進行操作。詳情請參閱 Cloud Pub/Sub Node.js API 參考說明文件

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

// Creates a client
const pubsub = new PubSub();

/**
 * TODO(developer): Uncomment the following line to run the sample.
 */
// const topicName = 'my-topic';

// Retrieves the IAM policy for the topic
const [policy] = await pubsub.topic(topicName).iam.getPolicy();
console.log(`Policy for topic: %j.`, policy.bindings);

PHP

在嘗試這個範例之前,請至 Cloud Pub/Sub 快速入門導覽課程:使用用戶端程式庫,按照 PHP 設定說明進行操作。詳情請參閱 Cloud 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

在嘗試這個範例之前,請至 Cloud Pub/Sub 快速入門導覽課程:使用用戶端程式庫,按照 Python 設定說明進行操作。詳情請參閱 Cloud Pub/Sub Python API 參考說明文件

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

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

在嘗試這個範例之前,請至 Cloud Pub/Sub 快速入門導覽課程:使用用戶端程式庫,按照 Ruby 設定說明進行操作。詳情請參閱 Cloud 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#

在嘗試這個範例之前,請至 Cloud Pub/Sub 快速入門導覽課程:使用用戶端程式庫,按照 C# 設定說明進行操作。詳情請參閱 Cloud Pub/Sub C# API 參考說明文件

Policy policy = new Policy
{
    Bindings =
    {
        new Binding { Role = roleToBeAddedToPolicy,
            Members = { member } }
    }
};
SetIamPolicyRequest request = new SetIamPolicyRequest
{
    Resource = new SubscriptionName(projectId, subscriptionId).ToString(),
    Policy = policy
};
Policy response = publisher.SetIamPolicy(request);
Console.WriteLine($"Subscription IAM Policy updated: {response}");

GCLOUD 指令

1. 取得訂閱政策。

gcloud beta pubsub subscriptions get-iam-policy projects/{your_project}/subscriptions/ \
{your_subscription} --format json > subscription_policy.json

2. 開啟 subscription_policy.json 並將適當角色授予適當成員,進而更新繫結。如要進一步瞭解如何處理 subscription_policy.json 檔案,請參閱 Cloud Identity and Access Management 政策說明文件

    {
      "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 beta pubsub subscriptions set-iam-policy projects/{your_project}/subscriptions/ \
{your_subscription} subscription_policy.json

Go

在嘗試這個範例之前,請至 Cloud Pub/Sub 快速入門導覽課程:使用用戶端程式庫,按照 Go 設定說明進行操作。詳情請參閱 Cloud Pub/Sub Go API 參考說明文件

sub := c.Subscription(subName)
policy, err := sub.IAM().Policy(ctx)
if err != nil {
	return 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 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.

Java

在嘗試這個範例之前,請至 Cloud Pub/Sub 快速入門導覽課程:使用用戶端程式庫,按照 Java 設定說明進行操作。詳情請參閱 Cloud Pub/Sub Java API 參考說明文件

try (SubscriptionAdminClient subscriptionAdminClient = SubscriptionAdminClient.create()) {
  ProjectSubscriptionName subscriptionName =
      ProjectSubscriptionName.of(projectId, subscriptionId);
  Policy policy = subscriptionAdminClient.getIamPolicy(subscriptionName.toString());
  // Create a role => members binding
  Binding binding =
      Binding.newBuilder()
          .setRole(Role.viewer().toString())
          .addMembers(Identity.allAuthenticatedUsers().toString())
          .build();
  // Update policy
  Policy updatedPolicy = policy.toBuilder().addBindings(binding).build();

  updatedPolicy =
      subscriptionAdminClient.setIamPolicy(subscriptionName.toString(), updatedPolicy);
  return updatedPolicy;
}

Node.js

在嘗試這個範例之前,請至 Cloud Pub/Sub 快速入門導覽課程:使用用戶端程式庫,按照 Node.js 設定說明進行操作。詳情請參閱 Cloud Pub/Sub Node.js API 參考說明文件

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

// Creates a client
const pubsub = new PubSub();

/**
 * TODO(developer): Uncomment the following line to run the sample.
 */
// const subscriptionName = 'my-sub';

// 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 pubsub
  .subscription(subscriptionName)
  .iam.setPolicy(newPolicy);
console.log(`Updated policy for subscription: %j`, updatedPolicy.bindings);

PHP

在嘗試這個範例之前,請至 Cloud Pub/Sub 快速入門導覽課程:使用用戶端程式庫,按照 PHP 設定說明進行操作。詳情請參閱 Cloud Pub/Sub PHP API 參考說明文件

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

在嘗試這個範例之前,請至 Cloud Pub/Sub 快速入門導覽課程:使用用戶端程式庫,按照 Python 設定說明進行操作。詳情請參閱 Cloud Pub/Sub Python API 參考說明文件

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

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_name, policy))

Ruby

在嘗試這個範例之前,請至 Cloud Pub/Sub 快速入門導覽課程:使用用戶端程式庫,按照 Ruby 設定說明進行操作。詳情請參閱 Cloud 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#

在嘗試這個範例之前,請至 Cloud Pub/Sub 快速入門導覽課程:使用用戶端程式庫,按照 C# 設定說明進行操作。詳情請參閱 Cloud Pub/Sub C# API 參考說明文件

Policy policy = new Policy
{
    Bindings =
        {
            new Binding { Role = roleToBeAddedToPolicy,
                Members = { member } }
        }
};
SetIamPolicyRequest request = new SetIamPolicyRequest
{
    Resource = new TopicName(projectId, topicId).ToString(),
    Policy = policy
};
Policy response = publisher.SetIamPolicy(request);
Console.WriteLine($"Topic IAM Policy updated: {response}");

GCLOUD 指令

1. 取得主題政策。

gcloud beta pubsub topics get-iam-policy projects/{your_project}/topics/{your_topic} \
--format json > topic_policy.json

2. 開啟 topic_policy.json 並將適當角色授予適當成員,進而更新繫結。如要進一步瞭解如何處理 subscription_policy.json 檔案,請參閱 Cloud Identity and Access Management 政策說明文件

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

3. 套用新的主題政策。

gcloud beta pubsub topics set-iam-policy projects/{your_project}/ \
topics/{your_topic} topic_policy.json

Go

在嘗試這個範例之前,請至 Cloud Pub/Sub 快速入門導覽課程:使用用戶端程式庫,按照 Go 設定說明進行操作。詳情請參閱 Cloud Pub/Sub Go API 參考說明文件

topic := c.Topic(topicName)
policy, err := topic.IAM().Policy(ctx)
if err != nil {
	return 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 {
	log.Fatalf("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.

Java

在嘗試這個範例之前,請至 Cloud Pub/Sub 快速入門導覽課程:使用用戶端程式庫,按照 Java 設定說明進行操作。詳情請參閱 Cloud Pub/Sub Java API 參考說明文件

try (TopicAdminClient topicAdminClient = TopicAdminClient.create()) {
  String topicName = ProjectTopicName.format(projectId, topicId);
  Policy policy = topicAdminClient.getIamPolicy(topicName);
  // add role -> members binding
  Binding binding =
      Binding.newBuilder()
          .setRole(Role.viewer().toString())
          .addMembers(Identity.allAuthenticatedUsers().toString())
          .build();
  // create updated policy
  Policy updatedPolicy = Policy.newBuilder(policy).addBindings(binding).build();
  updatedPolicy = topicAdminClient.setIamPolicy(topicName, updatedPolicy);
  return updatedPolicy;
}

Node.js

在嘗試這個範例之前,請至 Cloud Pub/Sub 快速入門導覽課程:使用用戶端程式庫,按照 Node.js 設定說明進行操作。詳情請參閱 Cloud Pub/Sub Node.js API 參考說明文件

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

// Creates a client
const pubsub = new PubSub();

/**
 * TODO(developer): Uncomment the following line to run the sample.
 */
// const topicName = 'my-topic';

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

PHP

在嘗試這個範例之前,請至 Cloud Pub/Sub 快速入門導覽課程:使用用戶端程式庫,按照 PHP 設定說明進行操作。詳情請參閱 Cloud Pub/Sub PHP API 參考說明文件

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

在嘗試這個範例之前,請至 Cloud Pub/Sub 快速入門導覽課程:使用用戶端程式庫,按照 Python 設定說明進行操作。詳情請參閱 Cloud Pub/Sub Python API 參考說明文件

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

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_name, policy))

Ruby

在嘗試這個範例之前,請至 Cloud Pub/Sub 快速入門導覽課程:使用用戶端程式庫,按照 Ruby 設定說明進行操作。詳情請參閱 Cloud 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#

在嘗試這個範例之前,請至 Cloud Pub/Sub 快速入門導覽課程:使用用戶端程式庫,按照 C# 設定說明進行操作。詳情請參閱 Cloud Pub/Sub C# API 參考說明文件

List<string> permissions = new List<string>();
permissions.Add("pubsub.subscriptions.get");
permissions.Add("pubsub.subscriptions.update");
TestIamPermissionsRequest request = new TestIamPermissionsRequest
{
    Resource = new SubscriptionName(_projectId, subscriptionId).ToString(),
    Permissions = { permissions }
};
TestIamPermissionsResponse response = publisher.TestIamPermissions(request);
return response;

GCLOUD 指令

gcloud iam list-testable-permissions https://pubsub.googleapis.com/v1/projects/ \
{your_project}/subscriptions/{your_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

在嘗試這個範例之前,請至 Cloud Pub/Sub 快速入門導覽課程:使用用戶端程式庫,按照 Go 設定說明進行操作。詳情請參閱 Cloud Pub/Sub Go API 參考說明文件

sub := c.Subscription(subName)
perms, err := sub.IAM().TestPermissions(ctx, []string{
	"pubsub.subscriptions.consume",
	"pubsub.subscriptions.update",
})
if err != nil {
	return nil, err
}
for _, perm := range perms {
	log.Printf("Allowed: %v", perm)
}

Java

在嘗試這個範例之前,請至 Cloud Pub/Sub 快速入門導覽課程:使用用戶端程式庫,按照 Java 設定說明進行操作。詳情請參閱 Cloud Pub/Sub Java API 參考說明文件

try (TopicAdminClient topicAdminClient = TopicAdminClient.create()) {
  List<String> permissions = new LinkedList<>();
  permissions.add("pubsub.subscriptions.get");
  ProjectSubscriptionName subscriptionName =
      ProjectSubscriptionName.of(projectId, subscriptionId);
  TestIamPermissionsResponse testedPermissions =
      topicAdminClient.testIamPermissions(subscriptionName.toString(), permissions);
  return testedPermissions;
}

Node.js

在嘗試這個範例之前,請至 Cloud Pub/Sub 快速入門導覽課程:使用用戶端程式庫,按照 Node.js 設定說明進行操作。詳情請參閱 Cloud Pub/Sub Node.js API 參考說明文件

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

// Creates a client
const pubsub = new PubSub();

/**
 * TODO(developer): Uncomment the following line to run the sample.
 */
// const subscriptionName = 'my-sub';

const permissionsToTest = [
  `pubsub.subscriptions.consume`,
  `pubsub.subscriptions.update`,
];

// Tests the IAM policy for the specified subscription
const [permissions] = await pubsub
  .subscription(subscriptionName)
  .iam.testPermissions(permissionsToTest);
console.log(`Tested permissions for subscription: %j`, permissions);

PHP

在嘗試這個範例之前,請至 Cloud Pub/Sub 快速入門導覽課程:使用用戶端程式庫,按照 PHP 設定說明進行操作。詳情請參閱 Cloud 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

在嘗試這個範例之前,請至 Cloud Pub/Sub 快速入門導覽課程:使用用戶端程式庫,按照 Python 設定說明進行操作。詳情請參閱 Cloud Pub/Sub Python API 參考說明文件

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

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))

Ruby

在嘗試這個範例之前,請至 Cloud Pub/Sub 快速入門導覽課程:使用用戶端程式庫,按照 Ruby 設定說明進行操作。詳情請參閱 Cloud 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#

在嘗試這個範例之前,請至 Cloud Pub/Sub 快速入門導覽課程:使用用戶端程式庫,按照 C# 設定說明進行操作。詳情請參閱 Cloud Pub/Sub C# API 參考說明文件

List<string> permissions = new List<string>();
permissions.Add("pubsub.topics.get");
permissions.Add("pubsub.topics.update");
TestIamPermissionsRequest request = new TestIamPermissionsRequest
{
    Resource = new TopicName(_projectId, topicId).ToString(),
    Permissions = { permissions }
};
TestIamPermissionsResponse response = publisher.TestIamPermissions(request);
return response;

GCLOUD 指令

gcloud beta iam list-testable-permissions https://pubsub.googleapis.com/v1/projects/ \
{your_project}/subscriptions/{your_subscription} --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

在嘗試這個範例之前,請至 Cloud Pub/Sub 快速入門導覽課程:使用用戶端程式庫,按照 Go 設定說明進行操作。詳情請參閱 Cloud Pub/Sub Go API 參考說明文件

topic := c.Topic(topicName)
perms, err := topic.IAM().TestPermissions(ctx, []string{
	"pubsub.topics.publish",
	"pubsub.topics.update",
})
if err != nil {
	return nil, err
}
for _, perm := range perms {
	log.Printf("Allowed: %v", perm)
}

Java

在嘗試這個範例之前,請至 Cloud Pub/Sub 快速入門導覽課程:使用用戶端程式庫,按照 Java 設定說明進行操作。詳情請參閱 Cloud Pub/Sub Java API 參考說明文件

try (TopicAdminClient topicAdminClient = TopicAdminClient.create()) {
  List<String> permissions = new LinkedList<>();
  permissions.add("pubsub.topics.get");
  ProjectTopicName topicName = ProjectTopicName.of(projectId, topicId);
  TestIamPermissionsResponse testedPermissions =
      topicAdminClient.testIamPermissions(topicName.toString(), permissions);
  return testedPermissions;
}

Node.js

在嘗試這個範例之前,請至 Cloud Pub/Sub 快速入門導覽課程:使用用戶端程式庫,按照 Node.js 設定說明進行操作。詳情請參閱 Cloud Pub/Sub Node.js API 參考說明文件

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

// Creates a client
const pubsub = new PubSub();

/**
 * TODO(developer): Uncomment the following line to run the sample.
 */
// const topicName = 'my-topic';

const permissionsToTest = [
  `pubsub.topics.attachSubscription`,
  `pubsub.topics.publish`,
  `pubsub.topics.update`,
];

// Tests the IAM policy for the specified topic
const [permissions] = await pubsub
  .topic(topicName)
  .iam.testPermissions(permissionsToTest);
console.log(`Tested permissions for topic: %j`, permissions);

PHP

在嘗試這個範例之前,請至 Cloud Pub/Sub 快速入門導覽課程:使用用戶端程式庫,按照 PHP 設定說明進行操作。詳情請參閱 Cloud 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

在嘗試這個範例之前,請至 Cloud Pub/Sub 快速入門導覽課程:使用用戶端程式庫,按照 Python 設定說明進行操作。詳情請參閱 Cloud Pub/Sub Python API 參考說明文件

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

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

在嘗試這個範例之前,請至 Cloud Pub/Sub 快速入門導覽課程:使用用戶端程式庫,按照 Ruby 設定說明進行操作。詳情請參閱 Cloud 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"

用途範例:跨專案通訊

Cloud Pub/Sub IAM 對於在跨專案通訊中獲得更好的存取體驗而言非常實用。例如,假設 Cloud 專案 A 中的服務帳戶想將訊息發布至 Cloud 專案 B 中的主題。您可以在 Cloud 專案 B 中授予服務帳戶「編輯」權限,來完成這項工作。但是,這個方法通常都太粗糙。您可以使用 IAM API 來實現更精細的存取層級。

例如,這個程式碼片段會使用 setIamPolicy() 方法和準備好的 topic_policy.json 檔案,將主題 projects/myproject/topics/mytopic 上的發布者角色授予服務帳戶 foobar@appspot.gserviceaccount.com

gcloud beta pubsub topics set-iam-policy projects/{your_project}/topics/ \
{your_topic} topic_policy.json

輸出:

Updated IAM policy for topic [your-topic].
bindings:
- members:
  - serviceAccount:foobar@appspot.gserviceaccount.com
  role: roles/pubsub.publisher
etag: BwWGrQYX6R4=

部分可用性行為

授權檢查仰賴 Cloud Identity and Access Management 子系統。為了確保資料作業 (發布與訊息調用) 能有穩定的低回應延遲時間,系統可能會依賴快取的 Cloud IAM 政策來避免延遲問題。如要進一步瞭解變更生效的時間,請參閱 Cloud IAM 說明文件

本頁內容對您是否有任何幫助?請提供意見:

傳送您對下列選項的寶貴意見...

這個網頁
Cloud Pub/Sub 說明文件