Berechtigungen für das Thema testen

Testet IAM-Berechtigungen für ein Thema.

Weitere Informationen

Eine ausführliche Dokumentation, die dieses Codebeispiel enthält, finden Sie hier:

Codebeispiel

C++

Folgen Sie der Einrichtungsanleitung für C++ in der Pub/Sub-Kurzanleitung zur Verwendung von Clientbibliotheken, bevor Sie dieses Beispiel ausprobieren. Weitere Informationen finden Sie in der Referenzdokumentation zur Pub/Sub C++ API.

Richten Sie Standardanmeldedaten für Anwendungen ein, um sich bei Pub/Sub zu authentifizieren. Weitere Informationen finden Sie unter Authentifizierung für eine lokale Entwicklungsumgebung einrichten.

namespace iam = google::cloud::iam;
namespace pubsub = google::cloud::pubsub;
[](std::string project_id, std::string topic_id) {
  auto const topic =
      pubsub::Topic(std::move(project_id), std::move(topic_id));
  auto client = iam::IAMPolicyClient(
      iam::MakeIAMPolicyConnection(pubsub::IAMPolicyOptions()));
  google::iam::v1::TestIamPermissionsRequest request;
  request.set_resource(topic.FullName());
  request.add_permissions("pubsub.topics.publish");
  request.add_permissions("pubsub.topics.update");

  auto response = client.TestIamPermissions(request);
  if (!response) throw std::move(response).status();
  std::cout << "Allowed permissions for topic " << topic.FullName() << ":";
  for (auto const& permission : response->permissions()) {
    std::cout << " " << permission;
  }
  std::cout << "\n";
}

C#

Folgen Sie der Einrichtungsanleitung für C# in der Pub/Sub-Kurzanleitung zur Verwendung von Clientbibliotheken, bevor Sie dieses Beispiel ausprobieren. Weitere Informationen finden Sie in der Referenzdokumentation zur Pub/Sub C# API.

Richten Sie Standardanmeldedaten für Anwendungen ein, um sich bei Pub/Sub zu authentifizieren. Weitere Informationen finden Sie unter Authentifizierung für eine lokale Entwicklungsumgebung einrichten.


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;
    }
}

Go

Folgen Sie der Einrichtungsanleitung für Go in der Pub/Sub-Kurzanleitung zur Verwendung von Clientbibliotheken, bevor Sie dieses Beispiel ausprobieren. Weitere Informationen finden Sie in der Referenzdokumentation zur Pub/Sub Go API.

Richten Sie Standardanmeldedaten für Anwendungen ein, um sich bei Pub/Sub zu authentifizieren. Weitere Informationen finden Sie unter Authentifizierung für eine lokale Entwicklungsumgebung einrichten.

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

Folgen Sie der Einrichtungsanleitung für Java in der Pub/Sub-Kurzanleitung zur Verwendung von Clientbibliotheken, bevor Sie dieses Beispiel ausprobieren. Weitere Informationen finden Sie in der Referenzdokumentation zur Pub/Sub Java API.

Richten Sie Standardanmeldedaten für Anwendungen ein, um sich bei Pub/Sub zu authentifizieren. Weitere Informationen finden Sie unter Authentifizierung für eine lokale Entwicklungsumgebung einrichten.


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

/**
 * 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);
}

Node.js

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

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

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

async function testTopicPermissions(topicNameOrId: string) {
  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 in der Pub/Sub-Kurzanleitung zur Verwendung von Clientbibliotheken, bevor Sie dieses Beispiel ausprobieren. Weitere Informationen finden Sie in der Referenzdokumentation zur Pub/Sub PHP API.

Richten Sie Standardanmeldedaten für Anwendungen ein, um sich bei Pub/Sub zu authentifizieren. Weitere Informationen finden Sie unter Authentifizierung für eine lokale Entwicklungsumgebung einrichten.

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

Folgen Sie der Einrichtungsanleitung für Python in der Pub/Sub-Kurzanleitung zur Verwendung von Clientbibliotheken, bevor Sie dieses Beispiel ausprobieren. Weitere Informationen finden Sie in der Referenzdokumentation zur Pub/Sub Python API.

Richten Sie Standardanmeldedaten für Anwendungen ein, um sich bei Pub/Sub zu authentifizieren. Weitere Informationen finden Sie unter Authentifizierung für eine lokale Entwicklungsumgebung einrichten.

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

Folgen Sie der Einrichtungsanleitung für Ruby in der Pub/Sub-Kurzanleitung zur Verwendung von Clientbibliotheken, bevor Sie dieses Beispiel ausprobieren. Weitere Informationen finden Sie in der Referenzdokumentation zur Pub/Sub Ruby API.

Richten Sie Standardanmeldedaten für Anwendungen ein, um sich bei Pub/Sub zu authentifizieren. Weitere Informationen finden Sie unter Authentifizierung für eine lokale Entwicklungsumgebung einrichten.

# 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"

Nächste Schritte

Informationen zum Suchen und Filtern von Codebeispielen für andere Google Cloud-Produkte finden Sie im Google Cloud-Beispielbrowser.