Objekt-ACL abrufen, die nach Nutzer gefiltert ist

Die nach Nutzern gefilterte Access Control List (ACL) für ein Objekt in einem Cloud Storage-Bucket aufrufen.

Codebeispiel

C++

Weitere Informationen finden Sie in der API-Referenzdokumentation zu Cloud Storage C++.

Richten Sie die Standardanmeldedaten für Anwendungen ein, um sich bei Cloud Storage zu authentifizieren. Weitere Informationen finden Sie unter Authentifizierung für Clientbibliotheken einrichten.

namespace gcs = ::google::cloud::storage;
using ::google::cloud::StatusOr;
[](gcs::Client client, std::string const& bucket_name,
   std::string const& object_name, std::string const& entity) {
  StatusOr<gcs::ObjectAccessControl> acl =
      client.GetObjectAcl(bucket_name, object_name, entity);

  if (!acl) throw std::move(acl).status();
  std::cout << "ACL entry for " << acl->entity() << " in object "
            << acl->object() << " in bucket " << acl->bucket() << " is "
            << *acl << "\n";
}

C#

Weitere Informationen finden Sie in der API-Referenzdokumentation zu Cloud Storage C#.

Richten Sie die Standardanmeldedaten für Anwendungen ein, um sich bei Cloud Storage zu authentifizieren. Weitere Informationen finden Sie unter Authentifizierung für Clientbibliotheken einrichten.


using Google.Apis.Storage.v1.Data;
using Google.Cloud.Storage.V1;
using System;
using System.Collections.Generic;
using System.Linq;

public class PrintFileAclForUserSample
{
    public IEnumerable<ObjectAccessControl> PrintFileAclForUser(
        string bucketName = "your-unique-bucket-name",
        string objectName = "your-object-name",
        string userEmail = "user@iam.gserviceaccount.com")
    {
        var storage = StorageClient.Create();
        var storageObject = storage.GetObject(bucketName, objectName, new GetObjectOptions
        {
            Projection = Projection.Full
        });

        var fileAclForUser = storageObject.Acl.Where((acl) => acl.Entity == $"user-{userEmail}");
        foreach (var acl in fileAclForUser)
        {
            Console.WriteLine($"{acl.Role}:{acl.Entity}");
        }

        return fileAclForUser;
    }
}

Go

Weitere Informationen finden Sie in der API-Referenzdokumentation zu Cloud Storage Go.

Richten Sie die Standardanmeldedaten für Anwendungen ein, um sich bei Cloud Storage zu authentifizieren. Weitere Informationen finden Sie unter Authentifizierung für Clientbibliotheken einrichten.

import (
	"context"
	"fmt"
	"io"

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

// printFileACLForUser lists ACL of the specified object with filter.
func printFileACLForUser(w io.Writer, bucket, object string, entity storage.ACLEntity) error {
	// bucket := "bucket-name"
	// object := "object-name"
	// entity := storage.AllAuthenticatedUsers
	ctx := context.Background()
	client, err := storage.NewClient(ctx)
	if err != nil {
		return fmt.Errorf("storage.NewClient: %w", err)
	}
	defer client.Close()

	rules, err := client.Bucket(bucket).ACL().List(ctx)
	if err != nil {
		return fmt.Errorf("ACLHandle.List: %w", err)
	}
	for _, r := range rules {
		if r.Entity == entity {
			fmt.Fprintf(w, "ACL rule role: %v\n", r.Role)
		}
	}
	return nil
}

Java

Weitere Informationen finden Sie in der API-Referenzdokumentation zu Cloud Storage Java.

Richten Sie die Standardanmeldedaten für Anwendungen ein, um sich bei Cloud Storage zu authentifizieren. Weitere Informationen finden Sie unter Authentifizierung für Clientbibliotheken einrichten.


import com.google.cloud.storage.Acl;
import com.google.cloud.storage.Acl.User;
import com.google.cloud.storage.Blob;
import com.google.cloud.storage.BlobId;
import com.google.cloud.storage.Storage;
import com.google.cloud.storage.StorageOptions;

public class PrintBlobAclForUser {

  public static void printBlobAclForUser(String bucketName, String blobName, String userEmail)
      throws Exception {

    // The ID to give your GCS bucket
    // String bucketName = "your-unique-bucket-name";

    // The name of the blob/file that you wish to view Acls of
    // String blobName = "your-blob-name";

    // The email of the user whose acl is being retrieved.
    // String userEmail = "someuser@domain.com"

    try (Storage storage = StorageOptions.newBuilder().build().getService()) {
      Blob blob = storage.get(BlobId.of(bucketName, blobName));
      Acl blobAcl = blob.getAcl(new User(userEmail));
      if (blobAcl != null) {
        String userRole = blobAcl.getRole().name();
        System.out.println("User " + userEmail + " has role " + userRole);
      } else {
        System.out.println("User " + userEmail + " not found");
      }
    }
  }
}

Node.js

Weitere Informationen finden Sie in der API-Referenzdokumentation zu Cloud Storage Node.js.

Richten Sie die Standardanmeldedaten für Anwendungen ein, um sich bei Cloud Storage zu authentifizieren. Weitere Informationen finden Sie unter Authentifizierung für Clientbibliotheken einrichten.

/**
 * TODO(developer): Uncomment the following lines before running the sample.
 */
// The ID of your GCS bucket
// const bucketName = 'your-unique-bucket-name';

// The ID of your GCS file
// const fileName = 'your-file-name';

// The email address of the user to check
// const userEmail = 'user-email-to-check';

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

// Creates a client
const storage = new Storage();

async function printFileAclForUser() {
  const options = {
    // Specify the user
    entity: `user-${userEmail}`,
  };

  // Gets the user's ACL for the file
  const [aclObject] = await storage
    .bucket(bucketName)
    .file(fileName)
    .acl.get(options);

  console.log(`${aclObject.role}: ${aclObject.entity}`);
}

printFileAclForUser().catch(console.error);

PHP

Weitere Informationen finden Sie in der API-Referenzdokumentation zu Cloud Storage PHP.

Richten Sie die Standardanmeldedaten für Anwendungen ein, um sich bei Cloud Storage zu authentifizieren. Weitere Informationen finden Sie unter Authentifizierung für Clientbibliotheken einrichten.

use Google\Cloud\Storage\StorageClient;

/**
 * Print an entity role for a file ACL.
 *
 * @param string $bucketName The name of your Cloud Storage bucket.
 *        (e.g. 'my-bucket')
 * @param string $objectName The name of your Cloud Storage object.
 *        (e.g. 'my-object')
 * @param string $entity The entity for which to query access controls.
 *        (e.g. 'user-example@domain.com')
 */
function print_file_acl_for_user(
    string $bucketName,
    string $objectName,
    string $entity
): void {
    $storage = new StorageClient();
    $bucket = $storage->bucket($bucketName);
    $object = $bucket->object($objectName);
    $acl = $object->acl();
    $item = $acl->get(['entity' => $entity]);
    printf('%s: %s' . PHP_EOL, $item['entity'], $item['role']);
}

Python

Weitere Informationen finden Sie in der API-Referenzdokumentation zu Cloud Storage Python.

Richten Sie die Standardanmeldedaten für Anwendungen ein, um sich bei Cloud Storage zu authentifizieren. Weitere Informationen finden Sie unter Authentifizierung für Clientbibliotheken einrichten.

from google.cloud import storage


def print_blob_acl_for_user(bucket_name, blob_name, user_email):
    """Prints out a blob's access control list for a given user."""

    storage_client = storage.Client()
    bucket = storage_client.bucket(bucket_name)
    blob = bucket.blob(blob_name)

    # Reload fetches the current ACL from Cloud Storage.
    blob.acl.reload()

    # You can also use `group`, `domain`, `all_authenticated` and `all` to
    # get the roles for different types of entities.
    roles = blob.acl.user(user_email).get_roles()

    print(roles)

Ruby

Weitere Informationen finden Sie in der API-Referenzdokumentation zu Cloud Storage Ruby.

Richten Sie die Standardanmeldedaten für Anwendungen ein, um sich bei Cloud Storage zu authentifizieren. Weitere Informationen finden Sie unter Authentifizierung für Clientbibliotheken einrichten.

# The ID of your GCS bucket
# bucket_name = "your-unique-bucket-name"
# file_name   = "Name of a file in the Storage bucket"
# email       = "Google Cloud Storage ACL Entity email"

require "google/cloud/storage"

storage = Google::Cloud::Storage.new
bucket  = storage.bucket bucket_name
file    = bucket.file file_name

puts "Permissions for #{email}:"
puts "OWNER"  if file.acl.owners.include?  email
puts "READER" if file.acl.readers.include? email

Weitere Informationen

Wenn Sie nach Codebeispielen für andere Produkte von Google Cloud suchen und filtern möchten, können Sie den Beispielbrowser fürGoogle Cloud verwenden.