Inhaber aus einem Bucket entfernen

Inhaberzugriff auf einen Cloud Storage-Bucket entfernen.

Weitere Informationen

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

Codebeispiel

C++

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

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

namespace gcs = ::google::cloud::storage;
using ::google::cloud::StatusOr;
[](gcs::Client client, std::string const& bucket_name,
   std::string const& entity) {
  StatusOr<gcs::BucketMetadata> original_metadata =
      client.GetBucketMetadata(bucket_name, gcs::Projection::Full());
  if (!original_metadata) throw std::move(original_metadata).status();

  std::vector<gcs::BucketAccessControl> original_acl =
      original_metadata->acl();
  auto it = std::find_if(original_acl.begin(), original_acl.end(),
                         [entity](gcs::BucketAccessControl const& entry) {
                           return entry.entity() == entity &&
                                  entry.role() ==
                                      gcs::BucketAccessControl::ROLE_OWNER();
                         });

  if (it == original_acl.end()) {
    std::cout << "Could not find entity " << entity
              << " with role OWNER in bucket " << bucket_name << "\n";
    return;
  }

  gcs::BucketAccessControl owner = *it;
  google::cloud::Status status =
      client.DeleteBucketAcl(bucket_name, owner.entity());

  if (!status.ok()) throw std::runtime_error(status.message());
  std::cout << "Deleted ACL entry for " << owner.entity() << " in bucket "
            << bucket_name << "\n";
}

C#

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

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


using Google.Cloud.Storage.V1;
using System;
using System.Linq;

public class RemoveBucketOwnerSample
{
    public void RemoveBucketOwner(
        string bucketName = "your-unique-bucket-name",
        string userEmail = "dev@iam.gserviceaccount.com")
    {
        var storage = StorageClient.Create();
        var bucket = storage.GetBucket(bucketName, new GetBucketOptions { Projection = Projection.Full });
        if (bucket.Acl == null)
        {
            Console.WriteLine("No owner to remove");
        }
        else
        {
            bucket.Acl = bucket.Acl.Where(acl => !(acl.Entity == $"user-{userEmail}" && acl.Role == "OWNER")).ToList();
            var updatedBucket = storage.UpdateBucket(bucket);
            Console.WriteLine($"Removed user {userEmail} from bucket {bucketName}.");
        }
    }
}

Go

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

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

import (
	"context"
	"fmt"

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

// removeBucketOwner removes ACL from a bucket.
func removeBucketOwner(bucket string, entity storage.ACLEntity) error {
	// bucket := "bucket-name"
	// entity := storage.AllUsers
	ctx := context.Background()
	client, err := storage.NewClient(ctx)
	if err != nil {
		return fmt.Errorf("storage.NewClient: %w", err)
	}
	defer client.Close()

	acl := client.Bucket(bucket).ACL()
	if err := acl.Delete(ctx, entity); err != nil {
		return fmt.Errorf("ACLHandle.Delete: %w", err)
	}
	return nil
}

Java

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

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


import com.google.cloud.storage.Acl.User;
import com.google.cloud.storage.Bucket;
import com.google.cloud.storage.Storage;
import com.google.cloud.storage.StorageOptions;

public class RemoveBucketOwner {

  public static void removeBucketOwner(String projectId, String bucketName, String userEmail) {

    // The ID of your GCP project
    // String projectId = "your-project-id";

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

    // Email of the user you wish to remove as an owner
    // String userEmail = "someuser@domain.com"

    Storage storage = StorageOptions.newBuilder().setProjectId(projectId).build().getService();
    Bucket bucket = storage.get(bucketName);
    User ownerToRemove = new User(userEmail);

    boolean success = bucket.deleteAcl(ownerToRemove);
    if (success) {
      System.out.println("Removed user " + userEmail + " as an owner on " + bucketName);
    } else {
      System.out.println("User " + userEmail + " was not found");
    }
  }
}

Node.js

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

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

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

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

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

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

async function removeBucketOwner() {
  // Removes the user from the access control list of the bucket. You can use
  // deleteAllUsers(), deleteDomain(), deleteProject(), deleteGroup(), and
  // deleteAllAuthenticatedUsers() to remove access for different types of entities.
  await storage.bucket(bucketName).acl.owners.deleteUser(userEmail);

  console.log(`Removed user ${userEmail} from bucket ${bucketName}.`);
}

removeBucketOwner().catch(console.error);

PHP

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

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

use Google\Cloud\Storage\StorageClient;

/**
 * Delete an entity from a bucket's default ACL.
 *
 * @param string $bucketName The name of your Cloud Storage bucket.
 *        (e.g. 'my-bucket')
 * @param string $entity The entity for which to update access controls.
 *        (e.g. 'user-example@domain.com')
 */
function delete_bucket_acl(string $bucketName, string $entity): void
{
    $storage = new StorageClient();
    $bucket = $storage->bucket($bucketName);
    $acl = $bucket->acl();
    $acl->delete($entity);
    printf('Deleted %s from gs://%s ACL' . PHP_EOL, $entity, $bucketName);
}

Python

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

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

from google.cloud import storage

def remove_bucket_owner(bucket_name, user_email):
    """Removes a user from the access control list of the given bucket."""
    # bucket_name = "your-bucket-name"
    # user_email = "name@example.com"

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

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

    # You can also use `group`, `domain`, `all_authenticated` and `all` to
    # remove access for different types of entities.
    bucket.acl.user(user_email).revoke_read()
    bucket.acl.user(user_email).revoke_write()
    bucket.acl.user(user_email).revoke_owner()
    bucket.acl.save()

    print(f"Removed user {user_email} from bucket {bucket_name}.")

Ruby

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

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

# project_id  = "Your Google Cloud project ID"
# The ID of your GCS bucket
# bucket_name = "your-unique-bucket-name"
# email       = "Google Cloud Storage ACL Entity email"

require "google/cloud/storage"

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

bucket.acl.delete email

puts "Removed ACL permissions for #{email} from #{bucket_name}"

Nächste Schritte

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