创建和管理访问控制列表 (ACL)

概览

本页面介绍如何使用访问控制列表 (ACL) 控制存储桶和对象的访问权限。ACL 是一种机制,可用于定义谁有权访问您的存储桶和对象,以及他们具有何种级别的访问权限。

请参阅 ACL 概览,详细了解您是否应使用 ACL 来控制对资源的访问。

所需的角色

如需获得创建和管理 ACL 所需的权限,请让您的管理员向您授予包含要为其创建和管理 ACL 的对象的存储桶的 Storage Admin (roles/storage.admin) IAM 角色。

此预定义角色包含创建和管理 ACL 所需的权限。如需查看所需的确切权限,请展开所需权限部分:

所需权限

  • storage.buckets.get
  • storage.buckets.list
    • 只有在使用 Google Cloud 控制台执行本页面上的任务时,才需要此权限。
  • storage.buckets.setIamPolicy
  • storage.buckets.update
  • storage.objects.get
  • storage.objects.getIamPolicy
  • storage.objects.setIamPolicy
  • storage.objects.update

您还可以通过自定义角色获得这些权限。

如需了解如何授予存储桶的角色,请参阅将 IAM 与存储桶搭配使用

设置或修改 ACL

控制台

  1. 转到 Google Cloud 控制台中的 Cloud Storage 浏览器。
    转到 Cloud Storage 浏览器

  2. 在存储桶列表中,找到包含要修改其 ACL 的对象的存储桶并点击其名称。

  3. 点击要为其设置或修改 ACL 的对象的名称。

  4. 点击修改访问权限

    此时将打开一个权限对话框,其中包含该对象的当前 ACL。

  5. 点击 + 添加条目

  6. 选择要向其授予权限的实体类型。

    实体指定了获得权限的对象的类型(例如,用户或群组)。如需查看受支持的实体值列表,请参阅访问控制范围

  7. 名称中输入值。

    名称标识了特定的用户、群组或其他实体类型。如需查看受支持的名称值列表,请参阅访问控制范围

    实体名称共同定义了权限适用的对象。

  8. 访问权限中选择一个值。

    访问权限定义了您要在对象上设置的权限。 如需查看受支持的访问权限值列表,请参阅访问控制权限

  9. 点击保存

如需了解如何在 Google Cloud 控制台中获取失败的 Cloud Storage 操作的详细错误信息,请参阅问题排查

命令行

如需添加、修改或移除对象上的单个授权,请使用带有相关标志的 objects update 命令:

gcloud storage objects update gs://BUCKET_NAME/OBJECT_NAME FLAG

其中:

  • BUCKET_NAME 是包含所修改对象的存储桶的名称。例如 example-travel-maps

  • OBJECT_NAME 是要修改的对象的名称。例如 paris.jpg

  • FLAG 是以下值之一:

    • --add-acl-grant,以及您要添加或修改的授权。例如 --add-acl-grant=entity=user-jane@gmail.com,role=READER

    • --remove-acl-grant 以及您要移除其访问权限的实体。例如 --remove-acl-grant=user-jane@gmail.com

如需替换对象的所有 ACL,请执行以下操作:

  1. 在 JSON 或 YAML 格式的文件中定义 ACL。

  2. 使用带有 --acl-file 标志的 objects update 命令:

    gcloud storage objects update gs://BUCKET_NAME/OBJECT_NAME --acl-file=FILE_LOCATION

    其中:

    • BUCKET_NAME 是包含 ACL 所适用对象的存储桶的名称。例如 example-travel-maps

    • OBJECT_NAME 是 ACL 所适用对象的名称。例如 paris.jpg

    • FILE_LOCATION 是包含您定义的 ACL 的文件的本地路径。例如 Desktop/acls.json

示例 ACL 文件的内容如下所示。这些 ACL 向项目 867489160491 的所有者以及用户 jane@gmail.com 授予对象 paris.jpgOWNER 权限,以及向 gs-announce 群组成员授予此对象的 READER 权限:

[
  {
    "entity": "project-owners-867489160491",
    "role": "OWNER",
    "projectTeam": {
      "projectNumber": "867489160491",
      "team": "owners"
    },
  },
  {
    "entity": "user-jane@gmail.com",
    "email": "jane@gmail.com",
    "role": "OWNER"
  },
  {
    "entity": "group-gs-announce@googlegroups.com",
    "email": "gs-announce@googlegroups.com",
    "role": "READER"
  }
]

客户端库

C++

如需了解详情,请参阅 Cloud Storage C++ API 参考文档

如需向 Cloud Storage 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为客户端库设置身份验证

以下示例将 ACL 添加到对象中:

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> patched_acl =
      client.CreateObjectAcl(bucket_name, object_name, entity,
                             gcs::ObjectAccessControl::ROLE_OWNER());

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

以下示例从对象中移除 ACL:

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::ObjectMetadata> original_metadata = client.GetObjectMetadata(
      bucket_name, object_name, gcs::Projection::Full());
  if (!original_metadata) throw std::move(original_metadata).status();

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

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

  gcs::ObjectAccessControl owner = *it;
  google::cloud::Status status =
      client.DeleteObjectAcl(bucket_name, object_name, owner.entity());

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

C#

如需了解详情,请参阅 Cloud Storage C# API 参考文档

如需向 Cloud Storage 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为客户端库设置身份验证

以下示例将 ACL 添加到对象中:


using Google.Apis.Storage.v1.Data;
using Google.Cloud.Storage.V1;
using System;

public class AddFileOwnerSample
{
    public Google.Apis.Storage.v1.Data.Object AddFileOwner(
        string bucketName = "your-unique-bucket-name",
        string objectName = "my-file-name",
        string userEmail = "dev@iam.gserviceaccount.com")
    {
        var storage = StorageClient.Create();
        var storageObject = storage.GetObject(bucketName, objectName, new GetObjectOptions
        {
            Projection = Projection.Full
        });

        storageObject.Acl.Add(new ObjectAccessControl
        {
            Bucket = bucketName,
            Entity = $"user-{userEmail}",
            Role = "OWNER",
        });
        var updatedObject = storage.UpdateObject(storageObject);
        Console.WriteLine($"Added user { userEmail} as an owner on file { objectName}.");
        return updatedObject;
    }
}

以下示例从对象中移除 ACL:


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

public class RemoveFileOwnerSample
{
    public void RemoveFileOwner(
        string bucketName = "your-unique-bucket-name",
        string objectName = "your-object-name",
        string userEmail = "dev@iam.gserviceaccount.com")
    {
        var storage = StorageClient.Create();
        var storageObject = storage.GetObject(bucketName, objectName, new GetObjectOptions { Projection = Projection.Full });
        if (storageObject.Acl == null)
        {
            Console.WriteLine("No owner to remove");
        }
        else
        {
            storageObject.Acl = storageObject.Acl.Where((acl) => !(acl.Entity == $"user-{userEmail}" && acl.Role == "OWNER")).ToList();
            var updatedObject = storage.UpdateObject(storageObject);
            Console.WriteLine($"Removed user {userEmail} from file {objectName}.");
        }
    }
}

Go

如需了解详情,请参阅 Cloud Storage Go API 参考文档

如需向 Cloud Storage 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为客户端库设置身份验证

以下示例将 ACL 添加到对象中:

import (
	"context"
	"fmt"

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

// addFileOwner adds ACL to the specified object.
func addFileOwner(bucket, object string, entity storage.ACLEntity) error {
	// bucket := "bucket-name"
	// object := "object-name"
	// entity := storage.AllUsers
	role := storage.RoleOwner

	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).Object(object).ACL()
	if err := acl.Set(ctx, entity, role); err != nil {
		return fmt.Errorf("ACLHandle.Set: %w", err)
	}
	return nil
}

以下示例从对象中移除 ACL:

import (
	"context"
	"fmt"

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

// removeFileOwner removes default ACL from the given object.
func removeFileOwner(bucket, object string, entity storage.ACLEntity) error {
	// bucket := "bucket-name"
	// object := "object-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).Object(object).ACL()
	if err := acl.Delete(ctx, entity); err != nil {
		return fmt.Errorf("ACLHandle.Delete: %w", err)
	}
	return nil
}

Java

如需了解详情,请参阅 Cloud Storage Java API 参考文档

如需向 Cloud Storage 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为客户端库设置身份验证

以下示例将 ACL 添加到对象中:


import com.google.cloud.storage.Acl;
import com.google.cloud.storage.Acl.Role;
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 AddFileOwner {

  public static void addFileOwner(
      String projectId, String bucketName, String userEmail, String blobName) {
    // 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 add as a file owner
    // String userEmail = "someuser@domain.com"

    // The name of the blob/file that you wish to modify permissions on
    // String blobName = "your-blob-name";

    Storage storage = StorageOptions.newBuilder().setProjectId(projectId).build().getService();
    Blob blob = storage.get(BlobId.of(bucketName, blobName));
    Acl newOwner = Acl.of(new User(userEmail), Role.OWNER);

    blob.createAcl(newOwner);
    System.out.println(
        "Added user "
            + userEmail
            + " as an owner on file "
            + blobName
            + " in bucket "
            + bucketName);
  }
}

以下示例从对象中移除 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 RemoveFileOwner {

  public static void removeFileOwner(
      String projectId, String bucketName, String userEmail, String blobName) {
    // 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 a file owner
    // String userEmail = "someuser@domain.com"

    // The name of the blob/file that you wish to modify permissions on
    // String blobName = "your-blob-name";

    Storage storage = StorageOptions.newBuilder().setProjectId(projectId).build().getService();
    Blob blob = storage.get(BlobId.of(bucketName, blobName));
    User ownerToRemove = new User(userEmail);

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

Node.js

如需了解详情,请参阅 Cloud Storage Node.js API 参考文档

如需向 Cloud Storage 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为客户端库设置身份验证

以下示例将 ACL 添加到对象中:

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

// The name of the file to access
// const fileName = 'file.txt';

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

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

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

async function addFileOwner() {
  await storage
    .bucket(bucketName)
    .file(fileName)
    .acl.owners.addUser(userEmail);

  console.log(`Added user ${userEmail} as an owner on file ${fileName}.`);
}

addFileOwner().catch(console.error);

以下示例从对象中移除 ACL:

/**
 * 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 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 removeFileOwner() {
  // Removes the user from the access control list of the file. You can use
  // deleteAllUsers(), deleteDomain(), deleteProject(), deleteGroup(), and
  // deleteAllAuthenticatedUsers() to remove access for different types of entities.
  await storage
    .bucket(bucketName)
    .file(fileName)
    .acl.owners.deleteUser(userEmail);

  console.log(`Removed user ${userEmail} from file ${fileName}.`);
}

removeFileOwner().catch(console.error);

PHP

如需了解详情,请参阅 Cloud Storage PHP API 参考文档

如需向 Cloud Storage 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为客户端库设置身份验证

以下示例将 ACL 添加到对象中:

use Google\Cloud\Storage\StorageClient;

/**
 * Add an entity and role to an object's 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 update access controls.
 *        (e.g. 'user-example@domain.com')
 * @param string $role The permissions to add for the specified entity.
 *        (e.g. 'OWNER')
 */
function add_object_acl(string $bucketName, string $objectName, string $entity, string $role): void
{
    $storage = new StorageClient();
    $bucket = $storage->bucket($bucketName);
    $object = $bucket->object($objectName);
    $acl = $object->acl();
    $acl->add($entity, $role);
    printf('Added %s (%s) to gs://%s/%s ACL' . PHP_EOL, $entity, $role, $bucketName, $objectName);
}

以下示例从对象中移除 ACL:

use Google\Cloud\Storage\StorageClient;

/**
 * Delete an entity from an object's 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 update access controls.
 *        (e.g. 'user-example@domain.com')
 */
function delete_object_acl(string $bucketName, string $objectName, string $entity): void
{
    $storage = new StorageClient();
    $bucket = $storage->bucket($bucketName);
    $object = $bucket->object($objectName);
    $acl = $object->acl();
    $acl->delete($entity);
    printf('Deleted %s from gs://%s/%s ACL' . PHP_EOL, $entity, $bucketName, $objectName);
}

Python

如需了解详情,请参阅 Cloud Storage Python API 参考文档

如需向 Cloud Storage 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为客户端库设置身份验证

以下示例将 ACL 添加到对象中:

from google.cloud import storage


def add_blob_owner(bucket_name, blob_name, user_email):
    """Adds a user as an owner on the given blob."""
    # bucket_name = "your-bucket-name"
    # blob_name = "your-object-name"
    # user_email = "name@example.com"

    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
    # grant access to different types of entities. You can also use
    # `grant_read` or `grant_write` to grant different roles.
    blob.acl.user(user_email).grant_owner()
    blob.acl.save()

    print(
        "Added user {} as an owner on blob {} in bucket {}.".format(
            user_email, blob_name, bucket_name
        )
    )

以下示例从对象中移除 ACL:

from google.cloud import storage


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

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

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

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

Ruby

如需了解详情,请参阅 Cloud Storage Ruby API 参考文档

如需向 Cloud Storage 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为客户端库设置身份验证

以下示例将 ACL 添加到对象中:

# 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

file.acl.add_owner email

puts "Added OWNER permission for #{email} to #{file_name}"

以下示例从对象中移除 ACL:

# 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

file.acl.delete email

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

REST API

JSON API

创建对象时,您可以在请求正文中指定 acl[] 属性,或在 insert 请求中指定 predefinedAcl 查询参数。如果是现有对象,请在 patchupdate 请求中指定 acl[] 属性或 predefinedAcl 查询参数。

如需查看对象 ACL 属性的定义,请参阅 ObjectAccessControls 资源。

  1. 在 JSON 文件中定义 ACL。

    例如,如果 ACL 向项目 867489160491 的所有者和用户 jane@gmail.com 授予 OWNER 权限,同时向 gs-announce 群组成员授予 READER 权限,那么您可以创建名为 acls.json 的文件,其中包含以下内容:

    {
    "acl": [
      {
        "entity": "project-owners-867489160491",
        "role": "OWNER",
        "projectTeam": {
          "projectNumber": "867489160491",
          "team": "owners"
        }
      },
      {
        "entity": "user-jane@gmail.com",
        "role": "OWNER",
        "email": "jane@gmail.com"
      },
      {
        "entity": "group-gs-announce@googlegroups.com",
        "role": "READER",
        "email": "gs-announce@googlegroups.com"
      }
    ]
    }
    
  2. 发送包含 JSON 文件的 patch 请求,并指定要设置该 ACL 的对象。

例如,以下 cURL 命令将文档 acls.json 中的 JSON 载荷应用到存储桶 example-travel-maps 中名为 paris.jpg 的对象上:

curl -X PATCH --data @acls.json -H "Content-Type: application/json" \
    -H "Authorization: Bearer $(gcloud auth print-access-token)" \
    https://storage.googleapis.com/storage/v1/b/example-travel-maps/o/paris.jpg

XML API

XML API 中,您使用 XML 格式的 ACL。您必须将一个 XML 文档附加到用于更改存储桶和对象 ACL 的请求的正文中。 当您获取存储桶和对象 ACL 时,系统会返回一个 XML 文档。该 XML 文档包含各个存储桶或对象 ACL 条目。

  • 使用 PUT Bucket 请求创建存储桶后,使用包含 ?acl 参数的另一个 PUT Bucket 请求来更改存储桶 ACL。

  • 使用 PUT Object 请求上传对象后,使用包含 ?acl 参数或 x-googl-acl 请求标头的另一个 PUT 请求来更改 ACL。

例如,以下 cURL 命令将文档 acls.xml 中的 XML 载荷应用到存储桶 example-travel-maps 中名为 paris.jpg 的对象上:

curl -X PUT --data-binary @acls.xml \
    -H "Authorization: Bearer $(gcloud auth print-access-token)" \
    https://storage.googleapis.com/example-travel-maps/paris.jpg?acl

为 XML 文档使用以下 ACL 语法:

元素 说明
AccessControlList EntriesOwner 元素的容器。
Owner DisplayNameID 元素的容器。此元素对于对象而言并不是必需的,因为对象的 Owner 始终是上传该对象的用户。在迁移情景中使用 Amazon S3 ACL 语法时,您将使用此元素。

Amazon Simple Storage Service™ 和 Amazon S3™ 是 Amazon.com, Inc. 或其关联公司在美国和/或其他国家/地区的商标。
ID 存储桶所有者的 Cloud Storage ID。
DisplayName 未实现。该值始终为空字符串。
Entries 零个或零个以上 Entry 元素的容器。
Entry ScopePermission 元素的容器。Entry 只能包含一个 Scope 和一个 Permission 元素。
Scope IDEmailAddressDomain 元素的容器,用于定义 ACL 范围。此元素必须具有一个 type 属性,包含下列中的一个值:UserByIDUserByEmailGroupByIDGroupByEmailGroupByDomainAllUsersAllAuthenticatedUsers
ID 被授予方的标识符(当权限条目由 ID 指定时)。
EmailAddress 被授予方的电子邮件标识符(当权限条目由电子邮件指定时)。
Domain 被授予方的网域标识符(当权限条目由网域指定时)。
Name 可选元素(您可以指定此元素,或者,如果范围是 UserByEmailGroupByEmail,则可以自动添加此元素)。
Permission 用于授予 READWRITEFULL_CONTROL 访问权限的权限。

使用 XML API 设置 ACL 时:

  • 您只能使用上述 XML 格式。
  • 您不能设置重复的范围。

    您可以在 ACL XML 中包含许多条目,但不能包含具有重复范围的条目。例如,您不能拥有两个具有相同范围元素 jane@example.com 的条目。

以下示例显示了不同的存储桶 ACL 条目:

<?xml version="1.0" encoding="UTF-8"?>
<AccessControlList>
  <Owner>
    <ID>00b4903a9721...</ID>
  </Owner>
  <Entries>
    <Entry>
      <Scope type="GroupById">
        <ID>00b4903a9722...</ID>
      </Scope>
      <Permission>FULL_CONTROL</Permission>
    </Entry>
    <Entry>
      <Scope type="GroupByDomain">
        <Domain>example.com</Domain>
      </Scope>
      <Permission>READ</Permission>
    </Entry>
    <Entry>
      <Scope type="GroupByEmail">
        <EmailAddress>gs-announce@googlegroups.com</EmailAddress>
      </Scope>
      <Permission>READ</Permission>
    </Entry>
    <Entry>
      <Scope type="UserByEmail">
        <EmailAddress>jane@gmail.com</EmailAddress>
        <Name>jane</Name>
      </Scope>
      <Permission>FULL_CONTROL</Permission>
    </Entry>
    <Entry>
      <Scope type="AllUsers"/>
      <Permission>READ</Permission>
    </Entry>
    <Entry>
      <Scope type="AllAuthenticatedUsers"/>
      <Permission>READ</Permission>
    </Entry>
  </Entries>
</AccessControlList>

设置 ACL XML 中的 Name 元素

从存储桶或对象检索 ACL 时,您可能会注意到,某些条目附加了一个额外的 <Name> 元素。例如,您可能会看到如下所示的条目:

<Entry>
  <Scope type="UserByEmail">
    <EmailAddress>jane@gmail.com</EmailAddress>
    <Name>Jane</Name>
  </Scope>
  <Permission>FULL_CONTROL</Permission>
</Entry>

在以下两种情况下,系统会填充这些可选的 <Name> 元素:

  1. 当存储桶或对象的 ACL 包含 <Name> 元素时

    设置 ACL 时,您可以选择在 ACL 条目中包含 <Name> 元素。您可以在 <Name> 元素中提供任何值,在移除或替换 ACL 之前,Cloud Storage 会一直记住这些值。如果您使用不易识别的标识符,则此方法十分实用。

  2. UserByEmailGroupByEmail 范围包含公开的 Google 个人资料时

    如果您使用这些范围中的任何一个,但未提供 <Name> 元素,则 Cloud Storage 会检查与该电子邮件地址关联的用户或 Google 群组是否拥有公开的 Google 个人资料(包含公开名称)。如果存在这种情况,Cloud Storage 会自动使用公开名称填充 <Name> 元素。

应用预定义的 ACL

您可以使用预定义的 ACL(自动应用多个针对特定情景进行自定义的条目),而不是如上所示逐个条目地指定整个 ACL。您可以使用 Google Cloud CLI、JSON API 或 XML API 将预定义的 ACL 应用到存储桶或对象上。

对于新的对象

要在对象上传期间将预定义 ACL 应用于对象,请执行以下操作:

控制台

您无法使用 Google Cloud 控制台应用预定义的 ACL。请改用 gcloud storage

命令行

gcloud storage cp 命令与 --predefined-acl 标志结合使用:

gcloud storage cp OBJECT gs://BUCKET_NAME --predefined-acl=PREDEFINED_ACL

例如,如需在将对象 paris.jpg 上传到存储桶 example-travel-maps 时应用预定义的 ACL bucketOwnerRead,请运行以下命令:

gcloud storage cp paris.jpg gs://example-travel-maps --predefined-acl=bucketOwnerRead

REST API

JSON API

insert 请求中使用 predefinedAcl 查询字符串参数来应用预定义的 ACL。

例如,如需在将对象 paris.jpg 上传到存储桶 example-travel-maps 时应用预定义的 ACL bucketOwnerRead,请运行以下命令:

curl -X POST --data-binary @paris.jpg -H "Content-Type: image/jpeg" \
    -H "Authorization: Bearer $(gcloud auth print-access-token)"  \
    "https://storage.googleapis.com/upload/storage/v1/b/example-travel-maps/o?name=paris.jpg&predefinedAcl=bucketOwnerRead"

XML API

Put Object 请求中使用 x-goog-acl 标头来应用预定义的 ACL。

例如,如需在将对象 paris.jpg 上传到存储桶 example-travel-maps 时应用预定义的 ACL bucket-owner-read,请运行以下命令:

curl -X PUT --upload-file paris.jpg -H "x-goog-acl: bucket-owner-read" \
    -H "Authorization: Bearer $(gcloud auth print-access-token)"  \
    https://storage.googleapis.com/example-travel-maps/paris.jpg

对于现有存储桶或对象

您还可以将预定义的 ACL 应用到现有存储桶或对象上,如果要将预定义的 ACL 更改为另一个预定义 ACL,或者要将自定义 ACL 更新为预定义 ACL,此方法非常有用。

控制台

您无法使用 Google Cloud 控制台应用预定义的 ACL。请改用 gcloud storage

命令行

使用带有 --predefined-acl 标志的 objects update 命令:

gcloud storage objects update gs://BUCKET_NAME/OBJECT_NAME --predefined-acl=PREDEFINED_ACL_NAME

例如,如需将预定义的 ACL private 应用于存储桶 example-travel-maps 中的对象 paris.jpg,请运行以下命令:

gcloud storage objects update gs://example-travel-maps/paris.jpg --predefined-acl=private

REST API

JSON API

patch 请求中使用 predefinedAcl 查询字符串参数并指定空的 acl 属性,以应用预定义的 ACL。

例如,如需将预定义的 ACL private 应用于存储桶 example-travel-maps 中的对象 paris.jpg,请运行以下命令:

curl -X PATCH --data '{"acl": []}'  -H "Content-Type: application/json" \
    -H "Authorization: Bearer $(gcloud auth print-access-token)"  \
    https://storage.googleapis.com/storage/v1/b/example-travel-maps/o/paris.jpg?predefinedAcl=private

XML API

Put Object 请求中使用 x-goog-acl 标头和 acl 查询字符串参数,但不要在请求中添加 XML 文档。

例如,如需将预定义的 ACL private 应用于存储桶 example-travel-maps 中的对象 paris.jpg,请运行以下命令:

curl -X PUT -H "Content-Length: 0" \
    -H "Authorization: Bearer $(gcloud auth print-access-token)" \
    -H "x-goog-acl: private" \
    https://storage.googleapis.com/example-travel-maps/paris.jpg?acl

设置默认对象 ACL

为避免每次创建新对象时都要设置 ACL,您可以在存储桶上设置默认对象 ACL。执行此操作后,添加到该存储桶但未明确应用 ACL 的每个新对象都将应用默认 ACL。例如,您可能只想允许特定用户组访问特定存储桶中的大多数对象。您可以更改默认对象 ACL,然后将对象添加到该存储桶中。这些添加的对象会自动应用您指定的默认对象 ACL;但是,您可以为特定对象指定不同的 ACL,在这种情况下,这些对象不会应用默认 ACL。

如需查看和更改存储桶的默认对象 ACL,请执行以下操作:

控制台

您无法使用 Google Cloud 控制台设置默认对象 ACL。请改用 gcloud storage

命令行

  1. 使用带有 --format 标志的 buckets describe 命令检索存储桶的默认对象 ACL:

    gcloud storage buckets describe gs://BUCKET_NAME --format="default(default_acl)"

    其中,BUCKET_NAME 是您要查看其默认对象 ACL 的存储桶的名称。例如 my-bucket

  2. 使用带有所需标志的 buckets update 命令修改存储桶的默认对象 ACL:

    gcloud storage buckets update gs://BUCKET_NAME FLAG

    其中:

    • BUCKET_NAME 是您要修改默认对象 ACL 的存储桶的名称。例如 my-bucket

    • FLAG 是以下值之一:

      • --add-default-object-acl-grant 是您要添加到存储桶的整体默认对象 ACL 中的授权。

      • --default-object-acl-file 和定义存储桶的新默认对象 ACL 的本地文件的路径。

      • --predefined-default-object-acl 以及您想要用来替换存储桶的现有默认对象 ACL 的预定义对象 ACL 的名称。

      • --remove-default-object-acl-grant 以及您要从存储桶的整体默认对象 ACL 中移除的实体。

客户端库

C++

如需了解详情,请参阅 Cloud Storage C++ API 参考文档

如需向 Cloud Storage 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为客户端库设置身份验证

以下示例将默认对象 ACL 添加到存储分区中:

namespace gcs = ::google::cloud::storage;
using ::google::cloud::StatusOr;
[](gcs::Client client, std::string const& bucket_name,
   std::string const& entity, std::string const& role) {
  StatusOr<gcs::ObjectAccessControl> default_object_acl =
      client.CreateDefaultObjectAcl(bucket_name, entity, role);
  if (!default_object_acl) throw std::move(default_object_acl).status();

  std::cout << "Role " << default_object_acl->role()
            << " will be granted default to " << default_object_acl->entity()
            << " on any new object created on bucket "
            << default_object_acl->bucket() << "\n"
            << "Full attributes: " << *default_object_acl << "\n";
}

以下示例从存储分区中删除默认对象 ACL:

namespace gcs = ::google::cloud::storage;
[](gcs::Client client, std::string const& bucket_name,
   std::string const& entity) {
  google::cloud::Status status =
      client.DeleteDefaultObjectAcl(bucket_name, entity);

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

C#

如需了解详情,请参阅 Cloud Storage C# API 参考文档

如需向 Cloud Storage 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为客户端库设置身份验证

以下示例输出存储桶的默认对象 ACL:


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

public class PrintBucketDefaultAclSample
{
    public IEnumerable<ObjectAccessControl> PrintBucketDefaultAcl(string bucketName = "your-unique-bucket-name")
    {
        var storage = StorageClient.Create();
        var bucket = storage.GetBucket(bucketName, new GetBucketOptions { Projection = Projection.Full });

        foreach (var acl in bucket.DefaultObjectAcl)
        {
            Console.WriteLine($"{acl.Role}:{acl.Entity}");
        }

        return bucket.DefaultObjectAcl;
    }
}

以下示例将默认对象 ACL 添加到存储分区中:


using Google.Apis.Storage.v1.Data;
using Google.Cloud.Storage.V1;
using System;

public class AddBucketDefaultOwnerSample
{
    public Bucket AddBucketDefaultOwner(
        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 });

        bucket.DefaultObjectAcl.Add(new ObjectAccessControl
        {
            Bucket = bucketName,
            Entity = $"user-{userEmail}",
            Role = "OWNER",
        });
        var updatedBucket = storage.UpdateBucket(bucket);
        Console.WriteLine($"Added user {userEmail} as a default owner on bucket {bucketName}.");
        return updatedBucket;
    }
}

以下示例从存储分区中删除默认对象 ACL:


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

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

Go

如需了解详情,请参阅 Cloud Storage Go API 参考文档

如需向 Cloud Storage 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为客户端库设置身份验证

以下示例将默认对象 ACL 添加到存储分区中:

import (
	"context"
	"fmt"

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

// addBucketDefaultOwner adds default ACL to the specified bucket.
func addBucketDefaultOwner(bucket string, entity storage.ACLEntity) error {
	// bucket := "bucket-name"
	// entity := storage.AllUsers
	role := storage.RoleOwner

	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).DefaultObjectACL()
	if err := acl.Set(ctx, entity, role); err != nil {
		return fmt.Errorf("ACLHandle.Set: %w", err)
	}
	return nil
}

以下示例从存储分区中删除默认对象 ACL:

import (
	"context"
	"fmt"

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

// deleteDefaultBucketACL removes default ACL from a bucket.
func removeBucketDefaultOwner(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).DefaultObjectACL()
	if err := acl.Delete(ctx, entity); err != nil {
		return fmt.Errorf("ACLHandle.Delete: %w", err)
	}
	return nil
}

Java

如需了解详情,请参阅 Cloud Storage Java API 参考文档

如需向 Cloud Storage 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为客户端库设置身份验证

以下示例将默认对象 ACL 添加到存储分区中:


import com.google.cloud.storage.Acl;
import com.google.cloud.storage.Acl.Role;
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 AddBucketDefaultOwner {

  public static void addBucketDefaultOwner(String bucketName, String userEmail) {

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

    // The email of the user you wish to add as a default owner
    // String userEmail = "someuser@domain.com"

    Storage storage = StorageOptions.newBuilder().build().getService();
    Bucket bucket = storage.get(bucketName);
    Acl newDefaultOwner = Acl.of(new User(userEmail), Role.OWNER);

    bucket.createDefaultAcl(newDefaultOwner);
    System.out.println("Added user " + userEmail + " as an owner on " + bucketName);
  }
}

以下示例从存储分区中删除默认对象 ACL:


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 RemoveBucketDefaultOwner {

  public static void removeBucketDefaultOwner(String bucketName, String userEmail) {

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

    // The email of the user you wish to remove as a default owner
    // String userEmail = "someuser@domain.com"

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

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

Node.js

如需了解详情,请参阅 Cloud Storage Node.js API 参考文档

如需向 Cloud Storage 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为客户端库设置身份验证

以下示例将默认对象 ACL 添加到存储分区中:

/**
 * 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 add
// const userEmail = 'user-email-to-add';

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

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

async function addBucketDefaultOwner() {
  // Makes the user an owner in the default ACL of the bucket. You can use
  // addAllUsers(), addDomain(), addProject(), addGroup(), and
  // addAllAuthenticatedUsers() to grant access to different types of entities.
  // You can also use "readers" and "writers" to grant different roles.
  await storage.bucket(bucketName).acl.default.owners.addUser(userEmail);

  console.log(`Added user ${userEmail} as an owner on bucket ${bucketName}.`);
}

addBucketDefaultOwner().catch(console.error);

以下示例从存储分区中删除默认对象 ACL:

/**
 * 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 removeBucketDefaultOwner() {
  // 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.default.owners.deleteUser(userEmail);

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

removeBucketDefaultOwner().catch(console.error);

PHP

如需了解详情,请参阅 Cloud Storage PHP API 参考文档

如需向 Cloud Storage 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为客户端库设置身份验证

以下示例将默认对象 ACL 添加到存储分区中:

use Google\Cloud\Storage\StorageClient;

/**
 * Add an entity and role to 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')
 * @param string $role The permissions to add for the specified entity.
 *        (e.g. 'OWNER')
 */
function add_bucket_default_acl(string $bucketName, string $entity, string $role): void
{
    $storage = new StorageClient();
    $bucket = $storage->bucket($bucketName);
    $acl = $bucket->defaultAcl();
    $acl->add($entity, $role);
    printf('Added %s (%s) to gs://%s default ACL' . PHP_EOL, $entity, $role, $bucketName);
}

以下示例从存储分区中删除默认对象 ACL:

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_default_acl(string $bucketName, string $entity): void
{
    $storage = new StorageClient();
    $bucket = $storage->bucket($bucketName);
    $acl = $bucket->defaultAcl();
    $acl->delete($entity);
    printf('Deleted %s from gs://%s default ACL' . PHP_EOL, $entity, $bucketName);
}

Python

如需了解详情,请参阅 Cloud Storage Python API 参考文档

如需向 Cloud Storage 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为客户端库设置身份验证

以下示例将默认对象 ACL 添加到存储分区中:

from google.cloud import storage


def add_bucket_default_owner(bucket_name, user_email):
    """Adds a user as an owner in the given bucket's default object access
    control list."""
    # 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
    # grant access to different types of entities. You can also use
    # `grant_read` or `grant_write` to grant different roles.
    bucket.default_object_acl.user(user_email).grant_owner()
    bucket.default_object_acl.save()

    print(
        "Added user {} as an owner in the default acl on bucket {}.".format(
            user_email, bucket_name
        )
    )

以下示例从存储分区中删除默认对象 ACL:

from google.cloud import storage


def remove_bucket_default_owner(bucket_name, user_email):
    """Removes a user from the access control list of the given bucket's
    default object access control list."""
    # 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.default_object_acl.user(user_email).revoke_read()
    bucket.default_object_acl.user(user_email).revoke_write()
    bucket.default_object_acl.user(user_email).revoke_owner()
    bucket.default_object_acl.save()

    print(
        f"Removed user {user_email} from the default acl of bucket {bucket_name}."
    )

Ruby

如需了解详情,请参阅 Cloud Storage Ruby API 参考文档

如需向 Cloud Storage 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为客户端库设置身份验证

以下示例将默认对象 ACL 添加到存储分区中:

# 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.default_acl.add_owner email

puts "Added default OWNER permission for #{email} to #{bucket_name}"

以下示例从存储分区中删除默认对象 ACL:

# 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.default_acl.delete email

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

REST API

JSON API

  1. 使用 GET 请求检索默认对象 ACL。例如:

    curl -X GET -H "Authorization: Bearer $(gcloud auth print-access-token)" \
        https://storage.googleapis.com/storage/v1/b/BUCKET_NAME?projection=full
    
  2. 使用 patch 请求替换默认对象 ACL。例如,以下请求将存储桶 example-travel-maps 的默认对象 ACL 替换为 defacls.json 中指定的 ACL:

    curl -X PATCH --data @defacls.json -H "Content-Type: application/json" -H "Authorization: Bearer $(gcloud auth print-access-token)" \
        https://storage.googleapis.com/storage/v1/b/example-travel-maps
    

    defacls.json 的示例:

    {
    "defaultObjectAcl": [
      {
        "email": "jane@gmail.com",
        "entity": "user-jane@gmail.com",
        "role": "READER"
      }
    ]
    }
    

XML API

  1. 使用 GET 请求(范围限定为您的存储桶)和 ?defaultObjectAcl 参数检索默认对象 ACL。例如:

    curl -X GET -H "Authorization: Bearer $(gcloud auth print-access-token)" \
        https://storage.googleapis.com/BUCKET_NAME?defaultObjectAcl
    
  2. 使用 PUT 请求(范围限定为您的存储桶)和 ?defaultObjectAcl 参数,将默认对象 ACL 替换为 acls.xml 中指定的 ACL。例如:

    curl -X PUT --data-binary @acls.xml -H "Authorization: Bearer $(gcloud auth print-access-token)" \
        http://storage.googleapis.com/BUCKET_NAME?defaultObjectAcl
    

    acls.xml 的示例:

    <AccessControlList>
      <Entries>
        <Entry>
          <Permission>FULL_CONTROL</Permission>
          <Scope type="UserByEmail">
            <EmailAddress>jane@gmail.com</EmailAddress>
          </Scope>
        </Entry>
      </Entries>
    </AccessControlList>
    

设置 ACL 中讨论了 ACL 的语法。 您还可以将预定义的 ACL 指定为默认对象 ACL。

如需将存储桶的默认对象 ACL 设为预定义的 ACL,请执行以下操作:

控制台

您无法使用 Google Cloud 控制台设置默认对象 ACL。请改用 gcloud storage

命令行

使用带有 --predefined-default-object-acl 标志的 buckets update 命令:

gcloud storage buckets update gs://BUCKET_NAME --predefined-default-object-acl=PREDEFINED_ACL

其中:

  • BUCKET_NAME 是您要修改默认对象 ACL 的存储桶的名称。例如 my-bucket

  • PREDEFINED_ACL 是有效的预定义 ACL 的名称。例如 projectPrivate

REST API

JSON API

使用 PUT 请求和 predefinedAcl 参数。

例如:

curl -X PUT -H "Content-Length: 0" -H "Authorization: Bearer $(gcloud auth print-access-token)" \
    https://storage.googleapis.com/storage/v1/b/BUCKET_NAME?predefinedAcl=private

XML API

使用 PUT 请求(范围限定为您的存储桶),并在请求中包含 ?defaultObjectAcl 参数和 x-goog-acl 标头。

例如:

curl -X PUT -H "x-goog-acl: project-private" -H "Content-Length: 0" -H "Authorization: Bearer $(gcloud auth print-access-token)" \
    http://storage.googleapis.com/BUCKET_NAME?defaultObjectAcl

新创建的存储桶的默认对象 ACL:

以下示例展示了在未指定自己的默认对象 ACL 作为请求一部分时自动应用于新创建的存储桶的默认对象 ACL。如需了解存储桶的默认对象 ACL 是否已更改,请将存储桶的当前默认对象 ACL 与以下示例进行比较。

控制台

您无法使用 Google Cloud 控制台处理默认对象 ACL。请改用 gcloud storage

命令行

在下面的示例中,项目 ID 为“123412341234”;您的项目 ID 将有所不同。

defaultObjectAcl:
– entity: project-owners-123412341234
  etag: CAE=
  kind: storage#objectAccessControl
  projectTeam:
    projectNumber: '123412341234'
    team: owners
  role: OWNER
– entity: project-editors-123412341234
  etag: CAE=
  kind: storage#objectAccessControl
  projectTeam:
    projectNumber: '123412341234'
    team: editors
  role: OWNER
– entity: project-viewers-123412341234
  etag: CAE=
  kind: storage#objectAccessControl
  projectTeam:
    projectNumber: '123412341234'
    team: viewers
  role: READER

REST API

JSON API

在下面的示例中,项目 ID 为“123412341234”;您的项目 ID 将有所不同。

"defaultObjectAcl": [
  {
    "kind": "storage#objectAccessControl",
    "entity": "project-owners-123412341234",
    "role": "OWNER",
    "projectTeam": {
      "projectNumber": "123412341234",
      "team": "owners"
    }
  },
  {
    "kind": "storage#objectAccessControl",
    "entity": "project-editors-123412341234",
    "role": "OWNER",
    "projectTeam": {
      "projectNumber": "123412341234",
      "team": "editors"
    }
  },
  {
    "kind": "storage#objectAccessControl",
    "entity": "project-viewers-123412341234",
    "role": "READER",
    "projectTeam": {
      "projectNumber": "123412341234",
      "team": "viewers"
    }
  }
]

XML API

在下面的示例中,项目角色 ID 以“00b4903a97...”开头;您的项目 ID 将有所不同。

<?xml version='1.0' encoding='UTF-8'?>
<AccessControlList>
  <Entries>
    <Entry>
      <Scope type='GroupById'>
        <ID>00b4903a9721...</ID>
      </Scope>
      <Permission>FULL_CONTROL</Permission>
    </Entry>
    <Entry>
      <Scope type='GroupById'>
        <ID>00b4903a9722...</ID>
      </Scope>
      <Permission>FULL_CONTROL</Permission>
    </Entry>
    <Entry>
      <Scope type='GroupById'>
        <ID>00b4903a9723...</ID>
      </Scope>
      <Permission>READ</Permission>
    </Entry>
  </Entries>
</AccessControlList>

请注意,新创建的存储桶的默认对象 ACL 等同于预定义的 projectPrivate ACL。

检索 ACL

如需获取现有资源的 ACL,请执行以下操作:

控制台

  1. 转到 Google Cloud 控制台中的 Cloud Storage 浏览器。
    转到 Cloud Storage 浏览器

  2. 导航到需要查看其 ACL 的对象。

  3. 从对象的下拉菜单中选择修改访问权限

    您会看到包含对象权限的权限对话框。

如需了解如何在 Google Cloud 控制台中获取失败的 Cloud Storage 操作的详细错误信息,请参阅问题排查

命令行

  1. 使用带有 --format 标志的 objects describe 命令检索对象的 ACL:

    gcloud storage objects describe gs://BUCKET_NAME/OBJECT_NAME --format="default(acl)"

    其中:

    • BUCKET_NAME 是包含要查看其 ACL 的对象的存储桶的名称,例如 my-bucket

    • OBJECT_NAME 是您要查看其 ACL 的对象的名称。例如 paris.jpg

客户端库

C++

如需了解详情,请参阅 Cloud Storage C++ API 参考文档

如需向 Cloud Storage 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为客户端库设置身份验证

以下示例获取了一个对象 ACL:

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

  if (!items) throw std::move(items).status();
  std::cout << "ACLs for object=" << object_name << " in bucket "
            << bucket_name << "\n";
  for (gcs::ObjectAccessControl const& acl : *items) {
    std::cout << acl.role() << ":" << acl.entity() << "\n";
  }
}

C#

如需了解详情,请参阅 Cloud Storage C# API 参考文档

如需向 Cloud Storage 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为客户端库设置身份验证

以下示例获取了一个对象 ACL:


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

public class PrintFileAclSample
{
    public IEnumerable<ObjectAccessControl> PrintObjectAcl(
        string bucketName = "your-unique-bucket-name",
        string objectName = "your-object-name")
    {
        var storage = StorageClient.Create();
        var storageObject = storage.GetObject(bucketName, objectName, new GetObjectOptions
        {
            Projection = Projection.Full
        });

        foreach (var acl in storageObject.Acl)
        {
            Console.WriteLine($"{acl.Role}:{acl.Entity}");
        }

        return storageObject.Acl;
    }
}

Go

如需了解详情,请参阅 Cloud Storage Go API 参考文档

如需向 Cloud Storage 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为客户端库设置身份验证

以下示例获取了一个对象 ACL:

import (
	"context"
	"fmt"
	"io"

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

// printFileACL lists ACL of the specified object.
func printFileACL(w io.Writer, bucket, object string) error {
	// bucket := "bucket-name"
	// object := "object-name"
	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).Object(object).ACL().List(ctx)
	if err != nil {
		return fmt.Errorf("ACLHandle.List: %w", err)
	}
	for _, rule := range rules {
		fmt.Fprintf(w, "ACL rule: %v\n", rule)
	}
	return nil
}

Java

如需了解详情,请参阅 Cloud Storage Java API 参考文档

如需向 Cloud Storage 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为客户端库设置身份验证

以下示例获取了一个对象 ACL:


import com.google.cloud.storage.Acl;
import com.google.cloud.storage.Blob;
import com.google.cloud.storage.BlobId;
import com.google.cloud.storage.Storage;
import com.google.cloud.storage.StorageOptions;
import java.util.List;

public class PrintFileAcl {

  public static void printFileAcl(String bucketName, String blobName) {

    // 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";

    Storage storage = StorageOptions.newBuilder().build().getService();
    Blob blob = storage.get(BlobId.of(bucketName, blobName));
    List<Acl> blobAcls = blob.getAcl();

    for (Acl acl : blobAcls) {

      // This will give you the role.
      // See https://cloud.google.com/storage/docs/access-control/lists#permissions
      String role = acl.getRole().name();

      // This will give you the Entity type (i.e. User, Group, Project etc.)
      // See https://cloud.google.com/storage/docs/access-control/lists#scopes
      String entityType = acl.getEntity().getType().name();

      System.out.printf("%s: %s %n", role, entityType);
    }
  }
}

Node.js

如需了解详情,请参阅 Cloud Storage Node.js API 参考文档

如需向 Cloud Storage 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为客户端库设置身份验证

以下示例获取了一个对象 ACL:

/**
 * 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';

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

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

async function printFileAcl() {
  // Gets the ACL for the file
  const [acls] = await storage.bucket(bucketName).file(fileName).acl.get();

  acls.forEach(acl => {
    console.log(`${acl.role}: ${acl.entity}`);
  });
}

printFileAcl().catch(console.error);

PHP

如需了解详情,请参阅 Cloud Storage PHP API 参考文档

如需向 Cloud Storage 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为客户端库设置身份验证

以下示例获取了一个对象 ACL:

use Google\Cloud\Storage\StorageClient;

/**
 * Print all entities and roles for an object's 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')
 */
function get_object_acl(string $bucketName, string $objectName): void
{
    $storage = new StorageClient();
    $bucket = $storage->bucket($bucketName);
    $object = $bucket->object($objectName);
    $acl = $object->acl();
    foreach ($acl->get() as $item) {
        printf('%s: %s' . PHP_EOL, $item['entity'], $item['role']);
    }
}

Python

如需了解详情,请参阅 Cloud Storage Python API 参考文档

如需向 Cloud Storage 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为客户端库设置身份验证

以下示例获取了一个对象 ACL:

from google.cloud import storage


def print_blob_acl(bucket_name, blob_name):
    """Prints out a blob's access control list."""

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

    for entry in blob.acl:
        print(f"{entry['role']}: {entry['entity']}")

Ruby

如需了解详情,请参阅 Cloud Storage Ruby API 参考文档

如需向 Cloud Storage 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为客户端库设置身份验证

以下示例获取了一个对象 ACL:

# 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 "ACL for #{file_name} in #{bucket_name}:"

file.acl.owners.each do |owner|
  puts "OWNER #{owner}"
end

file.acl.readers.each do |reader|
  puts "READER #{reader}"
end

REST API

JSON API

  1. 确保您拥有对象的 OWNER 权限。

  2. 使用 GET 请求检索对象的 ACL。

    对象 ACL 以 JSON 格式返回,并将附加到响应正文中。

例如,如需返回存储桶 example-travel-maps 中的对象 paris.jpg 的 ACL,请运行以下命令:

curl -X GET -H "Authorization: Bearer $(gcloud auth print-access-token)" \
    https://storage.googleapis.com/storage/v1/b/example-travel-maps/o/paris.jpg?projection=full

您应看到类似于如下所示的响应:

{
  "kind": "storage#object",
  "id": "example-travel-maps/paris.jpg/1412805837131000",
  "selfLink": "https://www.googleapis.com/storage/v1/b/example-travel-maps/o/paris.jpg",
  "name": "paris.jpg",
    "bucket": "example-travel-maps",
  ...
  "acl": [
    {
      ...
      "entity": "project-owners-867489160491",
      "role": "OWNER",
      "projectTeam": {
        "projectNumber": "867489160491",
        "team": "owners"
      },
      ...
    },
    {
      ...
      "entity": "user-jane@gmail.com",
      "role": "OWNER",
      "email": "jane@gmail.com",
      ...
    },
    {
      ...
      "entity": "group-gs-announce@googlegroups.com",
      "role": "READER",
      "email": "gs-announce@googlegroups.com",
      ...
    }
    ],
  "owner": {
    "entity": "user-jane@gmail.com"
  },
  ...
}

您还可以使用 objectAccessControls 资源 GET 方法返回对象 ACL 中的各个条目。

XML API

  1. 确保您在存储桶或对象上具有 FULL_CONTROL 权限。

  2. GET Object 请求中使用 acl 查询字符串参数,以检索存储桶或对象的 ACL。

ACL 以 XML 格式描述,随附在响应正文中。

例如,如需返回存储桶 example-travel-maps 中的对象 paris.jpg 的 ACL,请运行以下命令:

curl -X GET -H "Authorization: Bearer $(gcloud auth print-access-token)" \
    https://storage.googleapis.com/example-travel-maps/paris.jpg?acl

您应看到类似于如下所示的响应:

<?xml version="1.0" encoding="UTF-8"?>
<AccessControlList>
  <Owner>
    <ID>84fac329bceSAMPLE777d5d22b8SAMPLE77d85ac2SAMPLE2dfcf7c4adf34da46</ID>
    <Name>Owner Name</Name>
  </Owner>
  <Entries>
    <Entry>
      <Scope type="UserById">
        <ID>84fac329bceSAMPLE777d5d22b8SAMPLE77d85ac2SAMPLE2dfcf7c4adf34da46</ID>
        <Name>Name</Name>
      </Scope>
      <Permission>FULL_CONTROL</Permission>
    </Entry>
    <Entry>
      <Scope type="UserByEmail">
        <EmailAddress>jane@gmail.com</EmailAddress>
        <Name>Jane</Name>
      </Scope>
      <Permission>FULL_CONTROL</Permission>
    </Entry>
    <Entry>
      <Scope type="GroupByEmail">
        <EmailAddress>gs-announce@googlegroups.com</EmailAddress>
      </Scope>
      <Permission>READ</Permission>
    </Entry>
  </Entries>
</AccessControlList>

您还可以使用 ObjectAccessControls 资源的 JSON GET 方法返回特定的 ACL 条目。

后续步骤