Zugriffssteuerung mit IAM

In diesem Dokument werden die Zugriffssteuerungsoptionen beschrieben, die in Pub/Sub zur Verfügung stehen.

Überblick

Pub/Sub verwendet die Identitäts- und Zugriffsverwaltung (IAM) für die Zugriffssteuerung.

In Pub/Sub kann die Zugriffssteuerung auf Projektebene und auf der Ebene einzelner Ressourcen konfiguriert werden. Beispiel:

  • Zugriff je nach Thema oder Abo und nicht für das gesamte Cloud-Projekt gewähren.

    Wenn Sie nur Lesezugriff auf ein einzelnes Thema oder Abo haben, können Sie es nicht über die Google Cloud Console aufrufen. Stattdessen können Sie die Google Cloud CLI verwenden.

  • Zugriff mit begrenzten Möglichkeiten gewähren, zum Beispiel zum Veröffentlichen von Nachrichten nur zu einem Thema oder zum Erhalten von Nachrichten aus einem Abo ohne Löschen des Themas oder Abos.

  • Einer Gruppe von Entwicklern Zugriff auf alle Pub/Sub-Ressourcen innerhalb eines Projekts gewähren

Eine ausführliche Beschreibung von IAM und den entsprechenden Funktionen finden Sie in der IAM-Dokumentation. Lesen Sie insbesondere den Abschnitt Zugriff auf Ressourcen erteilen, ändern und entziehen.

Jede Pub/Sub-Methode erfordert die erforderlichen Berechtigungen. Eine Liste der Berechtigungen und Rollen, die Pub/Sub IAM unterstützt, finden Sie im unteren Abschnitt Rollen.

Berechtigungen und Rollen

In diesem Abschnitt werden die von Pub/Sub IAM unterstützten Berechtigungen und Rollen beschrieben.

Erforderliche Berechtigungen

In der folgenden Tabelle sind die Berechtigungen aufgeführt, die zum Aufrufen der einzelnen Methoden erforderlich sind:

REST-Methode Erforderliche Berechtigungen
projects.snapshots.create pubsub.snapshots.create für das zugehörige Cloudprojekt und die Berechtigung pubsub.subscriptions.consume für das Quellabo.
projects.snapshots.delete pubsub.snapshots.delete für den angefragten Snapshot.
projects.snapshots.getIamPolicy pubsub.snapshots.getIamPolicy für den angefragten Snapshot.
projects.snapshots.list pubsub.snapshots.list für das angefragte Cloudprojekt.
projects.snapshots.patch pubsub.snapshots.update für den angefragten Snapshot.
projects.snapshots.setIamPolicy pubsub.snapshots.setIamPolicy für den angefragten Snapshot.
projects.snapshots.testIamPermissions
projects.subscriptions.acknowledge pubsub.subscriptions.consume für das angeforderte Abo.
projects.subscriptions.create pubsub.subscriptions.create für das zugehörige Cloudprojekt und pubsub.topics.attachSubscription für das angeforderte Thema. Wenn Sie ein Abo in Projekt A für ein Thema T in Projekt B erstellen möchten, müssen die entsprechenden Berechtigungen sowohl für Projekt A als auch für Thema T erteilt werden. In diesem Fall können Informationen zur Nutzeridentität in den Audit-Logs von Projekt B erfasst werden.
projects.subscriptions.delete pubsub.subscriptions.delete für das angeforderte Abo.
projects.subscriptions.get pubsub.subscriptions.get für das angeforderte Abo.
projects.subscriptions.getIamPolicy pubsub.subscriptions.getIamPolicy für das angeforderte Abo.
projects.subscriptions.list pubsub.subscriptions.list für das angefragte Cloudprojekt.
projects.subscriptions.modifyAckDeadline pubsub.subscriptions.consume für das angeforderte Abo.
projects.subscriptions.modifyPushConfig pubsub.subscriptions.update für das angeforderte Abo.
projects.subscriptions.patch pubsub.subscriptions.update für das angeforderte Abo.
projects.subscriptions.pull pubsub.subscriptions.consume für das angeforderte Abo.
projects.subscriptions.seek pubsub.subscriptions.consume für das angeforderte Abo und pubsub.snapshots.seek für den angeforderten Snapshot, falls vorhanden.
projects.subscriptions.setIamPolicy pubsub.subscriptions.setIamPolicy für das angeforderte Abo.
projects.subscriptions.testIamPermissions
projects.topics.create pubsub.topics.create für das zugehörige Cloudprojekt.
projects.topics.delete pubsub.topics.delete für das angeforderte Thema.
projects.topics.detachSubscription pubsub.topics.detachSubscription für das angeforderte Thema.
projects.topics.get pubsub.topics.get für das angeforderte Thema.
projects.topics.getIamPolicy pubsub.topics.getIamPolicy für das angeforderte Thema.
projects.topics.list pubsub.topics.list für das angefragte Cloudprojekt.
projects.topics.patch pubsub.topics.update für das angeforderte Thema.
projects.topics.publish pubsub.topics.publish für das angeforderte Thema.
projects.topics.setIamPolicy pubsub.topics.setIamPolicy für das angeforderte Thema.
projects.topics.subscriptions.list pubsub.topics.get für das angeforderte Thema.
projects.topics.testIamPermissions

Rollen

In der folgenden Tabelle sind alle Pub/Sub-Rollen und die mit jeder Rolle verknüpften Berechtigungen aufgeführt:

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

Zugriff über die Google Cloud Console steuern

In der Google Cloud Console können Sie die Zugriffssteuerung für Ihre Themen und Projekte verwalten.

So legen Sie Zugriffssteuerungen auf Projektebene fest:

  1. Öffnen Sie in der Google Cloud Console die Seite "IAM".

    IAM aufrufen

  2. Wählen Sie Ihr Projekt aus.

  3. Klicken Sie auf Hinzufügen.

  4. Geben Sie einen oder mehrere Hauptkontennamen ein.

  5. Wählen Sie aus der Liste Rolle auswählen die Rolle aus, die Sie gewähren möchten.

  6. Klicken Sie auf Speichern.

  7. Prüfen Sie, ob das Hauptkonto mit der Rolle aufgelistet wird, die Sie ihm zugewiesen haben.

So legen Sie Zugriffssteuerungen für Themen und Abos fest:

  1. Rufen Sie in der Google Cloud Console die Pub/Sub-Liste Themen auf.

    Themen aufrufen

  2. Wählen Sie bei Bedarf Ihr Pub/Sub-fähiges Projekt aus.

  3. Führen Sie einen der folgenden Schritte aus:

    • Wählen Sie die Themen aus, um Rollen für ein oder mehrere Themen festzulegen.

    • Klicken Sie auf die Themen-ID, um Rollen für ein Abo festzulegen, das mit einem Thema verknüpft ist. Klicken Sie auf der Seite Themendetails auf die Abo-ID. Die Seite Abodetails wird angezeigt.

  4. Wenn das Infofeld ausgeblendet ist, klicken Sie auf Infofeld ansehen.

  5. Klicken Sie auf dem Tab Berechtigungen auf Hauptkonto hinzufügen.

  6. Geben Sie einen oder mehrere Hauptkontennamen ein.

  7. Wählen Sie aus der Liste Rolle auswählen die Rolle aus, die Sie gewähren möchten.

  8. Klicken Sie auf Speichern.

Zugriff über die IAM API steuern

Mit der IAM API von Pub/Sub können Sie Richtlinien für einzelne Themen und Abos in einem Projekt festlegen und abrufen sowie die Berechtigungen eines Nutzers für eine bestimmte Ressource testen. Wie bei den herkömmlichen Pub/Sub-Methoden können Sie die IAM API-Methoden über die Clientbibliotheken, den API Explorer oder direkt über HTTP aufrufen.

Beachten Sie, dass Sie mit der IAM API von Pub/Sub keine Richtlinien auf Google Cloud-Projektebene verwalten können.

Die folgenden Abschnitte enthalten Beispiele zum Festlegen und Abrufen von Richtlinien sowie zum Testen der Berechtigungen, die ein Aufrufer für eine bestimmte Ressource hat.

Richtlinie abrufen

Mit der Methode getIamPolicy() können Sie eine vorhandene Richtlinie abrufen. Diese Methode gibt ein JSON-Objekt zurück, das die Richtlinien enthält, die mit der Ressource verbunden sind.

Es folgt Beispielcode zum Abrufen von Richtlinien für ein Abo:

C#

Bevor Sie dieses Beispiel testen, folgen Sie der Einrichtungsanleitung für C# in der Schnellstart-Anleitung: Clientbibliotheken verwenden. Weitere Informationen finden Sie in der Referenzdokumentation zur 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

Rufen Sie die Abo-Richtlinie ab:

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

Ausgabe:

   {
     "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"
       }
     ]
   }

Einfach loslegen (Go)

Bevor Sie dieses Beispiel testen, folgen Sie der Einrichtungsanleitung für Go in der Schnellstart-Anleitung: Clientbibliotheken verwenden. Weitere Informationen finden Sie in der Referenzdokumentation zur 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

Bevor Sie dieses Beispiel testen, folgen Sie der Einrichtungsanleitung für Java in der Kurzanleitung: Clientbibliotheken verwenden. Weitere Informationen finden Sie in der Referenzdokumentation zur 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

Bevor Sie dieses Beispiel testen, folgen Sie der Einrichtungsanleitung für PHP in der Schnellstart-Anleitung: Clientbibliotheken verwenden. Weitere Informationen finden Sie in der Referenzdokumentation zur 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

Bevor Sie dieses Beispiel testen, folgen Sie der Einrichtungsanleitung für PHP in der Schnellstart-Anleitung: Clientbibliotheken verwenden. Weitere Informationen finden Sie in der Referenzdokumentation zur 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

Folgen Sie der Einrichtungsanleitung für PHP unter Schnellstart: Clientbibliotheken verwenden, bevor Sie dieses Beispiel ausprobieren. Weitere Informationen finden Sie in der Referenzdokumentation zur 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

Bevor Sie dieses Beispiel testen, folgen Sie der Einrichtungsanleitung für Python in der Schnellstart-Anleitung: Clientbibliotheken verwenden. Weitere Informationen finden Sie in der Referenzdokumentation zur 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

Bevor Sie dieses Beispiel testen, folgen Sie der Einrichtungsanleitung für Ruby in der Schnellstart-Anleitung: Clientbibliotheken verwenden. Weitere Informationen finden Sie in der Referenzdokumentation zur 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
Es folgt Beispielcode zum Abrufen von Richtlinien für ein Thema:

C#

Bevor Sie dieses Beispiel testen, folgen Sie der Einrichtungsanleitung für C# in der Schnellstart-Anleitung: Clientbibliotheken verwenden. Weitere Informationen finden Sie in der Referenzdokumentation zur 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

Themenrichtlinie abrufen

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

Ausgabe:

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

Einfach loslegen (Go)

Bevor Sie dieses Beispiel testen, folgen Sie der Einrichtungsanleitung für Go in der Schnellstart-Anleitung: Clientbibliotheken verwenden. Weitere Informationen finden Sie in der Referenzdokumentation zur 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

Bevor Sie dieses Beispiel testen, folgen Sie der Einrichtungsanleitung für Java in der Kurzanleitung: Clientbibliotheken verwenden. Weitere Informationen finden Sie in der Referenzdokumentation zur 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

Bevor Sie dieses Beispiel testen, folgen Sie der Einrichtungsanleitung für PHP in der Schnellstart-Anleitung: Clientbibliotheken verwenden. Weitere Informationen finden Sie in der Referenzdokumentation zur 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

Folgen Sie der Einrichtungsanleitung für PHP unter Schnellstart: Clientbibliotheken verwenden, bevor Sie dieses Beispiel ausprobieren. Weitere Informationen finden Sie in der Referenzdokumentation zur 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

Bevor Sie dieses Beispiel testen, folgen Sie der Einrichtungsanleitung für Python in der Schnellstart-Anleitung: Clientbibliotheken verwenden. Weitere Informationen finden Sie in der Referenzdokumentation zur 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

Bevor Sie dieses Beispiel testen, folgen Sie der Einrichtungsanleitung für Ruby in der Schnellstart-Anleitung: Clientbibliotheken verwenden. Weitere Informationen finden Sie in der Referenzdokumentation zur 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

Richtlinie festlegen

Mit der Methode setIamPolicy() können Sie eine Richtlinie mit einer Ressource verknüpfen. Die Methode setIamPolicy() akzeptiert eine SetIamPolicyRequest, die eine festzulegende Richtlinie sowie die Ressource enthält, mit der die Richtlinie verknüpft ist. Sie gibt die entsprechende Richtlinie zurück.

Der folgende Beispielcode dient zum Festlegen von Richtlinien für ein Abo:

C#

Bevor Sie dieses Beispiel testen, folgen Sie der Einrichtungsanleitung für C# in der Schnellstart-Anleitung: Clientbibliotheken verwenden. Weitere Informationen finden Sie in der Referenzdokumentation zur 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. Speichern Sie die Richtlinie für das Abo.

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

2. Öffnen Sie subscription_policy.json und aktualisieren Sie die Bindungen, indem Sie den entsprechenden Hauptkonten die entsprechenden Rollen zuweisen. Weitere Informationen zum Arbeiten mit subscription_policy.json-Dateien finden Sie unter Richtlinie in der IAM-Dokumentation.

   {
     "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. Wenden Sie die neue Richtlinie für Abos an.

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

Einfach loslegen (Go)

Bevor Sie dieses Beispiel testen, folgen Sie der Einrichtungsanleitung für Go in der Schnellstart-Anleitung: Clientbibliotheken verwenden. Weitere Informationen finden Sie in der Referenzdokumentation zur 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

Bevor Sie dieses Beispiel testen, folgen Sie der Einrichtungsanleitung für Java in der Kurzanleitung: Clientbibliotheken verwenden. Weitere Informationen finden Sie in der Referenzdokumentation zur 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

Bevor Sie dieses Beispiel testen, folgen Sie der Einrichtungsanleitung für PHP in der Schnellstart-Anleitung: Clientbibliotheken verwenden. Weitere Informationen finden Sie in der Referenzdokumentation zur 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

Bevor Sie dieses Beispiel testen, folgen Sie der Einrichtungsanleitung für Python in der Schnellstart-Anleitung: Clientbibliotheken verwenden. Weitere Informationen finden Sie in der Referenzdokumentation zur 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

Bevor Sie dieses Beispiel testen, folgen Sie der Einrichtungsanleitung für Ruby in der Schnellstart-Anleitung: Clientbibliotheken verwenden. Weitere Informationen finden Sie in der Referenzdokumentation zur 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

Es folgt ein Abschnitt mit Beispielcode zum Festlegen von Richtlinien für ein Thema:

C#

Bevor Sie dieses Beispiel testen, folgen Sie der Einrichtungsanleitung für C# in der Schnellstart-Anleitung: Clientbibliotheken verwenden. Weitere Informationen finden Sie in der Referenzdokumentation zur 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. Speichern Sie die Richtlinie für das Thema.

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

2. Öffnen Sie topic_policy.json und aktualisieren Sie die Bindungen, indem Sie den entsprechenden Hauptkonten die entsprechenden Rollen zuweisen. Weitere Informationen zum Arbeiten mit subscription_policy.json-Dateien finden Sie unter Richtlinie in der IAM-Dokumentation.

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

3. Wenden Sie die neue Themenrichtlinie an.

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

Einfach loslegen (Go)

Bevor Sie dieses Beispiel testen, folgen Sie der Einrichtungsanleitung für Go in der Schnellstart-Anleitung: Clientbibliotheken verwenden. Weitere Informationen finden Sie in der Referenzdokumentation zur 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

Bevor Sie dieses Beispiel testen, folgen Sie der Einrichtungsanleitung für Java in der Kurzanleitung: Clientbibliotheken verwenden. Weitere Informationen finden Sie in der Referenzdokumentation zur 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

Bevor Sie dieses Beispiel testen, folgen Sie der Einrichtungsanleitung für PHP in der Schnellstart-Anleitung: Clientbibliotheken verwenden. Weitere Informationen finden Sie in der Referenzdokumentation zur 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

Bevor Sie dieses Beispiel testen, folgen Sie der Einrichtungsanleitung für Python in der Schnellstart-Anleitung: Clientbibliotheken verwenden. Weitere Informationen finden Sie in der Referenzdokumentation zur 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

Bevor Sie dieses Beispiel testen, folgen Sie der Einrichtungsanleitung für Ruby in der Schnellstart-Anleitung: Clientbibliotheken verwenden. Weitere Informationen finden Sie in der Referenzdokumentation zur 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

Berechtigungen testen

Mit der Methode testIamPermissions() können Sie prüfen, welche der angegebenen Berechtigungen für die angegebene Ressource hinzugefügt oder entfernt werden können. Als Parameter werden ein Ressourcenname und eine Reihe von Berechtigungen verwendet und der Teil der Berechtigungen zurückgegeben.

Es folgt Beispielcode zum Testen von Berechtigungen für ein Abo:

C#

Bevor Sie dieses Beispiel testen, folgen Sie der Einrichtungsanleitung für C# in der Schnellstart-Anleitung: Clientbibliotheken verwenden. Weitere Informationen finden Sie in der Referenzdokumentation zur 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

Ausgabe:

 [
    {
     "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"
   }
 ]

Einfach loslegen (Go)

Bevor Sie dieses Beispiel testen, folgen Sie der Einrichtungsanleitung für Go in der Schnellstart-Anleitung: Clientbibliotheken verwenden. Weitere Informationen finden Sie in der Referenzdokumentation zur 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

Bevor Sie dieses Beispiel testen, folgen Sie der Einrichtungsanleitung für Java in der Kurzanleitung: Clientbibliotheken verwenden. Weitere Informationen finden Sie in der Referenzdokumentation zur 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

Bevor Sie dieses Beispiel testen, folgen Sie der Einrichtungsanleitung für PHP in der Schnellstart-Anleitung: Clientbibliotheken verwenden. Weitere Informationen finden Sie in der Referenzdokumentation zur 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

Folgen Sie der Einrichtungsanleitung für PHP unter Schnellstart: Clientbibliotheken verwenden, bevor Sie dieses Beispiel ausprobieren. Weitere Informationen finden Sie in der Referenzdokumentation zur 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

Bevor Sie dieses Beispiel testen, folgen Sie der Einrichtungsanleitung für Python in der Schnellstart-Anleitung: Clientbibliotheken verwenden. Weitere Informationen finden Sie in der Referenzdokumentation zur 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

Bevor Sie dieses Beispiel testen, folgen Sie der Einrichtungsanleitung für Ruby in der Schnellstart-Anleitung: Clientbibliotheken verwenden. Weitere Informationen finden Sie in der Referenzdokumentation zur 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"

Es folgt Beispielcode zum Festlegen von Richtlinien für ein Thema:

C#

Bevor Sie dieses Beispiel testen, folgen Sie der Einrichtungsanleitung für C# in der Schnellstart-Anleitung: Clientbibliotheken verwenden. Weitere Informationen finden Sie in der Referenzdokumentation zur 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

Ausgabe

 [
   {
     "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"
   }
 ]

Einfach loslegen (Go)

Bevor Sie dieses Beispiel testen, folgen Sie der Einrichtungsanleitung für Go in der Schnellstart-Anleitung: Clientbibliotheken verwenden. Weitere Informationen finden Sie in der Referenzdokumentation zur 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

Bevor Sie dieses Beispiel testen, folgen Sie der Einrichtungsanleitung für Java in der Kurzanleitung: Clientbibliotheken verwenden. Weitere Informationen finden Sie in der Referenzdokumentation zur 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

Bevor Sie dieses Beispiel testen, folgen Sie der Einrichtungsanleitung für PHP in der Schnellstart-Anleitung: Clientbibliotheken verwenden. Weitere Informationen finden Sie in der Referenzdokumentation zur 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

Folgen Sie der Einrichtungsanleitung für PHP unter Schnellstart: Clientbibliotheken verwenden, bevor Sie dieses Beispiel ausprobieren. Weitere Informationen finden Sie in der Referenzdokumentation zur 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

Bevor Sie dieses Beispiel testen, folgen Sie der Einrichtungsanleitung für Python in der Schnellstart-Anleitung: Clientbibliotheken verwenden. Weitere Informationen finden Sie in der Referenzdokumentation zur 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

Bevor Sie dieses Beispiel testen, folgen Sie der Einrichtungsanleitung für Ruby in der Schnellstart-Anleitung: Clientbibliotheken verwenden. Weitere Informationen finden Sie in der Referenzdokumentation zur 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"

Beispielanwendungsfall: Projektübergreifende Kommunikation

Pub/Sub IAM ist nützlich, um bei projektübergreifender Kommunikation die Zugriffsrechte genau abzustimmen.

Angenommen, ein Dienstkonto im Cloud-Projekt A möchte Nachrichten zu einem Thema im Cloud-Projekt B veröffentlichen. Aktivieren Sie zuerst die Pub/Sub API in Projekt A.

Gewähren Sie dem Dienstkonto dann die Berechtigung Bearbeiten im Cloud-Projekt B. Dieser Ansatz ist jedoch oft zu grob. Mit der IAM API können Sie die Zugriffsebene noch präziser festlegen.

Projektübergreifende Kommunikation

Beispielsweise verwendet dieses Snippet die setIamPolicy()-Methode in project-b und eine vorbereitete topic_policy.json-Datei, um dem Dienstkonto foobar@project-a.iam.gserviceaccount.com von project-a die Publisher-Rolle für das Thema projects/project-b/topics/topic-b zu gewähren:

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

Verhalten bei teilweiser Verfügbarkeit

Die Autorisierungsprüfungen hängen vom IAM-Subsystem ab. Das System kann auf im Cache gespeicherte IAM-Richtlinien zurückgreifen, um eine konsistent niedrige Reaktionslatenz für Datenoperationen (Veröffentlichung und Nachrichtenverbrauch) zu bieten. Weitere Informationen dazu, wann Ihre Änderungen wirksam werden, finden Sie in der IAM-Dokumentation.