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

本页面介绍如何使用访问控制列表 (ACL) 控制存储分区和对象的访问权限。ACL 是一种机制,可用于定义谁有权访问您的存储分区和对象,以及他们具有何种级别的访问权限。要详细了解 ACL,请参阅 ACL 概览

要了解如何以其他方式控制存储分区和对象的访问权限,请参阅访问权限控制概览

准备工作

您应当使用 ACL 吗?

大多数情况下,我们建议您使用 Cloud Identity and Access Management (Cloud IAM) 来控制资源访问权限,因为它针对 Google Cloud Platform 的方方面面提供了企业级访问控制,并允许子资源(比如存储分区和对象)继承授予父资源(比如项目)的权限。有关在 Cloud Storage 中使用 Cloud IAM 的指南,请参阅使用 Cloud IAM 权限

如果您需要自定义对存储分区中单个对象的访问权限,则最适合使用 ACL,因为 Cloud IAM 权限适用于存储分区中的所有对象。但对适用于存储分区中所有对象的任何访问权限,您仍应使用 IAM,因为这可为您减轻需要完成的精细管理工作量。

您需要设置 ACL 吗?

根据您希望存储分区或对象具有的权限,您可能不一定需要设置 ACL。创建的存储分区和对象具有默认 ACL,而默认 ACL 可能已包含您希望这些存储分区或对象具有的权限。

使用以下准则决定是否应当设置 ACL。

对于存储分区:

Console

新创建的存储分区具有预定义的 project-private ACL。如果您的存储分区需要其他权限,请设置 ACL

gsutil

新存储分区将作为 project-private 添加。如果您的存储分区需要其他权限,请设置 ACL

JSON API

默认情况下,新存储分区将作为 project-private 添加。如果您的存储分区需要其他权限,请设置 ACL

XML API

新存储分区将作为 project-private 添加。如果您的存储分区需要其他权限,请设置 ACL

如上所述,每个存储分区都有一个默认对象 ACL,该 ACL 将应用于上传到该存储分区中且没有预定义 ACL 的所有对象,或者(如果使用的是 JSON API)具有请求中指定的 ACL 的所有对象。有关详情,请参阅默认对象 ACL

对于对象:

Console

上传的对象获得与存储分区对象相同的 ACL,系统会将上传者作为所有者添加到 ACL 中。如果您的对象需要其他权限,请设置 ACL

gsutil

添加新对象后,新对象将具有存储分区的默认对象 ACL。复制已存储在云中的对象时,您可以使用 -p 选项替换此行为。

JSON API

默认情况下,添加新对象后,新对象将具有存储分区的默认对象 ACL。

XML API

添加新对象后,新对象将具有存储分区的默认对象 ACL。

您应该使用哪个界面?

以下示例显示了如何使用 Google Cloud Platform Console、gsutil 命令行工具、Cloud Storage 客户端库以及 XML 和 JSON API 来配置访问控制。通过以下准则来选择要使用的方法:

  • 如果您刚开始了解访问控制,并且只希望修改单个对象的 ACL,请使用 GCP Console

  • 如果您刚开始了解访问控制,并且希望修改存储分区和对象的 ACL,请使用 gsutil

  • 如果您有某个 Cloud Storage 客户端库的使用经验,请使用此库来管理 ACL。

  • 如果您使用 API 来指定 ACL,则应该有发出 HTTP 请求的经验。您可以使用自己喜欢的工具或应用发送 HTTP 请求。在示例中,我们使用 cURL 工具。您可以从 OAuth 2.0 Playground 获取要在 cURL 示例中使用的授权令牌。

设置 ACL

您用于设置和获取 ACL 的工具或 API 决定了您使用的 ACL 语法。虽然各种 ACL 语法看起来有所不同,但它们包含相同的 ACL 信息:向范围授予权限的条目。

Console

  1. 转到 GCP Console 中的 Cloud Storage 浏览器。
    转到 Cloud Storage 浏览器

  2. 导航到需要修改其 ACL 的对象。

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

    您应看到一个类似于如下所示的权限对话框:

    此屏幕截图显示了包含四个条目的 ACL:

    • 在第一个条目中,特定项目(其项目编号为 867489140601)的全部所有者将获得此对象的“所有者”权限。
    • 在第二个条目中,特定项目(其项目编号为 867489140601)的所有修改者也会获得此对象的“所有者”权限。
    • 在第三个条目中,特定项目(其项目编号为 867489140601)的全部查看者将获得此对象的“读取者”权限。
    • 在第四个条目中,上传对象的用户将获得对象的“所有者”权限。对象上传者始终会被设为“所有者”,您无法移除该角色。
  4. 点击添加项目

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

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

  6. 名称中输入值。

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

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

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

    访问权限定义了您要在对象上设置的权限。如需了解各个支持的访问权限值,请参阅访问控制权限

  8. 点击保存

gsutil

使用 gsutil acl 来指定 ACL:

  • 要指定各个授权操作,请运行以下命令:

    gsutil acl ch -u [USER_EMAIL]:[PERMISSION] gs://[BUCKET_NAME]

  • 要指定预设的 ACL,请运行以下命令:

    gsutil acl set [CANNED_ACL_NAME] gs://[BUCKET_NAME]

  • 要以 JSON 格式指定 ACL,请运行以下命令:

    gsutil acl set [JSON_FILE] gs://[bucket-name]

    其中,[JSON_FILE] 包含以 JSON 格式指定的 ACL。

代码示例

C++

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

以下示例演示了如何为存储分区添加 ACL:

namespace gcs = google::cloud::storage;
using ::google::cloud::StatusOr;
[](gcs::Client client, std::string bucket_name, std::string entity) {
  StatusOr<gcs::BucketAccessControl> patched_acl =
      client.PatchBucketAcl(bucket_name, entity,
                            gcs::BucketAccessControlPatchBuilder().set_role(
                                gcs::BucketAccessControl::ROLE_OWNER()));

  if (!patched_acl) {
    throw std::runtime_error(patched_acl.status().message());
  }

  std::cout << "ACL entry for " << patched_acl->entity() << " 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 bucket_name, std::string object_name,
   std::string entity) {
  StatusOr<gcs::ObjectAccessControl> patched_acl =
      client.CreateObjectAcl(bucket_name, object_name, entity,
                             gcs::ObjectAccessControl::ROLE_OWNER());

  if (!patched_acl) {
    throw std::runtime_error(patched_acl.status().message());
  }

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

C#

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

以下示例演示了如何为存储分区添加 ACL:

private void AddBucketOwner(string bucketName, string userEmail)
{
    var storage = StorageClient.Create();
    var bucket = storage.GetBucket(bucketName, new GetBucketOptions()
    {
        Projection = Projection.Full
    });
    if (null == bucket.Acl)
    {
        bucket.Acl = new List<BucketAccessControl>();
    }
    bucket.Acl.Add(new BucketAccessControl()
    {
        Bucket = bucketName,
        Entity = $"user-{userEmail}",
        Role = "OWNER",
    });
    var updatedBucket = storage.UpdateBucket(bucket, new UpdateBucketOptions()
    {
        // Avoid race conditions.
        IfMetagenerationMatch = bucket.Metageneration,
    });
}

以下示例演示了如何为对象添加 ACL:

private void AddObjectOwner(string bucketName, string objectName,
    string userEmail)
{
    var storage = StorageClient.Create();
    var storageObject = storage.GetObject(bucketName, objectName,
        new GetObjectOptions() { Projection = Projection.Full });
    if (null == storageObject.Acl)
    {
        storageObject.Acl = new List<ObjectAccessControl>();
    }
    storageObject.Acl.Add(new ObjectAccessControl()
    {
        Bucket = bucketName,
        Entity = $"user-{userEmail}",
        Role = "OWNER",
    });
    var updatedObject = storage.UpdateObject(storageObject, new UpdateObjectOptions()
    {
        // Avoid race conditions.
        IfMetagenerationMatch = storageObject.Metageneration,
    });
}

Go

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

以下示例演示了如何为存储分区添加 ACL:

func addBucketACL(client *storage.Client, bucket string) error {
	ctx := context.Background()

	acl := client.Bucket(bucket).ACL()
	if err := acl.Set(ctx, storage.AllAuthenticatedUsers, storage.RoleReader); err != nil {
		return err
	}
	return nil
}

以下示例演示了如何为对象添加 ACL:

func addObjectACL(client *storage.Client, bucket, object string) error {
	ctx := context.Background()

	acl := client.Bucket(bucket).Object(object).ACL()
	if err := acl.Set(ctx, storage.AllAuthenticatedUsers, storage.RoleReader); err != nil {
		return err
	}
	return nil
}

Java

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

以下示例演示了如何为存储分区添加 ACL:

Acl acl = storage.createAcl(bucketName, Acl.of(User.ofAllAuthenticatedUsers(), Role.READER));

以下示例演示了如何为对象添加 ACL:

BlobId blobId = BlobId.of(bucketName, blobName, blobGeneration);
Acl acl = storage.createAcl(blobId, Acl.of(User.ofAllAuthenticatedUsers(), Role.READER));

Node.js

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

以下示例演示了如何为存储分区添加 ACL:

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

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

/**
 * TODO(developer): Uncomment the following line before running the sample.
 */
// const bucketName = 'Name of a bucket, e.g. my-bucket';
// const userEmail = 'Email of user to add, e.g. developer@company.com';

// Makes the user an owner 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.owners.addUser(userEmail);

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

以下示例演示了如何为对象添加 ACL:

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

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

/**
 * TODO(developer): Uncomment the following line before running the sample.
 */
// const bucketName = 'Name of a bucket, e.g. my-bucket';
// const filename = 'Name of file to access, e.g. file.txt';
// const userEmail = 'Email of user to add, e.g. developer@company.com';

// Makes the user an owner of the file. 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)
  .file(filename)
  .acl.owners.addUser(userEmail);

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

PHP

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

以下示例演示了如何为存储分区添加 ACL:

use Google\Cloud\Storage\StorageClient;

/**
 * Add an entity and role to a bucket's ACL.
 *
 * @param string $bucketName the name of your Cloud Storage bucket.
 * @param string $entity The entity to update access controls for.
 * @param string $role The permissions to add for the specified entity. May
 *        be one of 'OWNER', 'READER', or 'WRITER'.
 * @param array $options
 *
 * @return void
 */
function add_bucket_acl($bucketName, $entity, $role, $options = [])
{
    $storage = new StorageClient();
    $bucket = $storage->bucket($bucketName);
    $acl = $bucket->acl();
    $acl->add($entity, $role, $options);
    printf('Added %s (%s) to gs://%s ACL' . PHP_EOL, $entity, $role, $bucketName);
}

以下示例演示了如何为对象添加 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.
 * @param string $objectName the name of your Cloud Storage object.
 * @param string $entity The entity to update access controls for.
 * @param string $role The permissions to add for the specified entity. May
 *        be one of 'OWNER', 'READER', or 'WRITER'.
 * @param array $options
 *
 * @return void
 */
function add_object_acl($bucketName, $objectName, $entity, $role, $options = [])
{
    $storage = new StorageClient();
    $bucket = $storage->bucket($bucketName);
    $object = $bucket->object($objectName);
    $acl = $object->acl();
    $acl->add($entity, $role, $options);
    printf('Added %s (%s) to gs://%s/%s ACL' . PHP_EOL, $entity, $role, $bucketName, $objectName);
}

Python

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

以下示例演示了如何为存储分区添加 ACL:

def add_bucket_owner(bucket_name, user_email):
    """Adds a user as an owner on the given bucket."""
    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.acl.user(user_email).grant_owner()
    bucket.acl.save()

    print('Added user {} as an owner on bucket {}.'.format(
        user_email, bucket_name))

以下示例演示了如何为对象添加 ACL:

def add_blob_owner(bucket_name, blob_name, user_email):
    """Adds a user as an owner on the given blob."""
    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))

Ruby

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

以下示例演示了如何为存储分区添加 ACL:

# project_id  = "Your Google Cloud project ID"
# bucket_name = "Your Google Cloud Storage bucket name"
# email       = "Google Cloud Storage ACL Entity email"

require "google/cloud/storage"

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

bucket.acl.add_owner email

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

以下示例演示了如何为对象添加 ACL:

# project_id  = "Your Google Cloud project ID"
# bucket_name = "Your Google Cloud Storage 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 project_id: project_id
bucket  = storage.bucket bucket_name
file    = bucket.file file_name

file.acl.add_owner email

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

JSON API

创建存储分区时,您可以在插入请求中指定 acl[] 属性。如果是现有存储分区,请在 patch 更新请求中指定 acl[] 属性。

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

如需查看存储分区和对象 ACL 属性的定义,请分别参阅 BucketAccessControlsObjectAccessControls 资源。

以下示例显示了不同的存储分区 ACL 条目。

"acl": [
{
"kind": "storage#bucketAccessControl",
"id": "example-bucket/project-owners-123412341234",
"selfLink": "https://www.googleapis.com/storage/v1/b/example-bucket/acl/project-owners-123412341234",
"bucket": "example-bucket",
"entity": "project-owners-123412341234",
"role": "OWNER",
"projectTeam": {
       "projectNumber": "123412341234",
       "team": "owners"
},
"etag": "CDk="
},
{
"kind": "storage#bucketAccessControl",
"id": "example-bucket/project-editors-123412341234",
"selfLink": "https://www.googleapis.com/storage/v1/b/example-bucket/acl/project-editors-123412341234",
"bucket": "example-bucket",
"entity": "project-editors-123412341234",
"role": "OWNER",
"projectTeam": {
     "projectNumber": "123412341234",
     "team": "editors"
},
"etag": "CDk="
},
{
"kind": "storage#bucketAccessControl",
"id": "example-bucket/project-viewers-123412341234",
"selfLink": "https://www.googleapis.com/storage/v1/b/example-bucket/acl/project-viewers-123412341234",
"bucket": "example-bucket",
"entity": "project-viewers-123412341234",
"role": "READER",
"projectTeam": {
     "projectNumber": "123412341234",
     "team": "viewers"
},
"etag": "CDk="
},
{
"kind": "storage#bucketAccessControl",
"id": "example-bucket/group-gs-announce@googlegroups.com",
"selfLink": "https://www.googleapis.com/storage/v1/b/example-bucket/acl/group-gs-announce@googlegroups.com",
"bucket": "example-bucket",
"entity": "group-gs-announce@googlegroups.com",
"role": "READER",
"email": "gs-announce@googlegroups.com",
"etag": "CDk="
},
{
"kind": "storage#bucketAccessControl",
"id": "example-bucket/user-jane@gmail.com",
"selfLink": "https://www.googleapis.com/storage/v1/b/example-bucket/acl/user-jane@gmail.com",
"bucket": "example-bucket",
"entity": "user-jane@gmail.com",
"role": "READER",
"email": "jane@gmail.com",
"etag": "CDk="
},
{
"kind": "storage#bucketAccessControl",
"id": "example-bucket/allUsers",
"selfLink": "https://www.googleapis.com/storage/v1/b/example-bucket/acl/allUsers",
"bucket": "example-bucket",
"entity": "allUsers",
"role": "READER",
"etag": "CDk="
},
{
"kind": "storage#bucketAccessControl",
"id": "example-bucket/allAuthenticatedUsers",
"selfLink": "https://www.googleapis.com/storage/v1/b/example-bucket/acl/allAuthenticatedUsers",
"bucket": "example-bucket",
"entity": "allAuthenticatedUsers",
"role": "READER",
"etag": "CDk="
}
]

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。

为 XML API 使用以下 ACL 语法。请注意,RELAX NG 紧凑语法格式架构描述了 Google ACL XML 的确切格式要求。

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

Amazon Simple Storage Service™ 和 Amazon S3™ 是 Amazon.com, Inc. 或其关联公司在美国和/或其他国家/地区的商标。
ID 存储分区所有者的 Google 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="GroupById">
        <ID>00b4903a9723...</ID>
      </Scope>
      <Permission>FULL_CONTROL</Permission>
    </Entry>
    <Entry>
      <Scope type="GroupById">
        <ID>00b4903a9724...</ID>
      </Scope>
      <Permission>READ</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>READ</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 会一直记住这些值。如果您使用不易识别的标识符(比如 Google Cloud Storage ID),则此方法十分实用。

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

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

应用预定义的 ACL

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

对于新的对象

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

Console

您无法使用 GCP Console 应用预定义的 ACL。请改为使用 gsutil。

gsutil

搭配 -a 选项使用 gsutil cp 命令来应用预定义的 ACL:

gsutil cp -a [PREDEFINED_ACL] [OBJECT] gs://[BUCKET_NAME]

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

gsutil cp -a bucket-owner-read paris.jpg gs://example-travel-maps

JSON API

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

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

curl -X POST --data-binary @paris.jpg -H "Content-Type: image/jpeg" 
-H "Authorization: Bearer ya29.AHES6ZRVmB7fkLtd1XTmq6mo0S1wqZZi3-Lh_s-6Uw7p8vtgSwg"
"https://www.googleapis.com/upload/storage/v1/b/example-travel-maps/o?name=paris.jpg&predefinedAcl=bucketOwnerRead"

请求类似于如下示例:

POST /upload/storage/v1/b/example-travel-maps/o?name=paris.jpg&amppredefinedAcl=bucketOwnerRead HTTP/1.1
Host: www.googleapis.com
Content-Type: image/jpeg
Authorization: Bearer ya29.AHES6ZRVmB7fkLtd1XTmq6mo0S1wqZZi3-Lh_s-6Uw7p8vtgSwg
Content-Length: 12345
Date: Fri, 10 Oct 2014 00:02:38 GMT

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 ya29.AHES6ZRVmB7fkLtd1XTmq6mo0S1wqZZi3-Lh_s-6Uw7p8vtgSwg"
https://storage.googleapis.com/example-travel-maps/paris.jpg

请求类似于如下示例:

PUT /paris.jpg HTTP/1.1
Host: example-travel-maps.storage.googleapis.com
Date: Thu, 09 Oct 2014 23:06:08 GMT
Content-Length: 12345
Content-Type: image/jpg
x-goog-acl: bucket-owner-read
Authorization: Bearer ya29.AHES6ZRVmB7fkLtd1XTmq6mo0S1wqZZi3-Lh_s-6Uw7p8vtgSwg

12345 bytes in entity body

对于现有存储分区或对象

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

Console

您无法使用 GCP Console 应用预定义的 ACL。请改为使用 gsutil。

gsutil

使用 gsutil acl set 命令来应用预定义的 ACL:

gsutil acl set [PREDEFINED_ACL] gs://[BUCKET_NAME]/[OBJECT_NAME]

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

gsutil acl set private gs://example-travel-maps/paris.jpg

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 ya29.AHES6ZRVmB7fkLtd1XTmq6mo0S1wqZZi3-Lh_s-6Uw7p8vtgSwg"
https://www.googleapis.com/storage/v1/b/example-travel-maps/o/paris.jpg?predefinedAcl=private

请求类似于如下示例:

PATCH /storage/v1/b/example-travel-maps/o/paris.jpg?predefinedAcl=private HTTP/1.1
Host: www.googleapis.com
Content-Type: application/json
Authorization: Bearer ya29.AHES6ZRVmB7fkLtd1XTmq6mo0S1wqZZi3-Lh_s-6Uw7p8vtgSwg
Content-Length: 11
Date: Fri, 10 Oct 2014 18:57:59 GMT

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 ya29.AHES6ZRVmB7fkLtd1XTmq6mo0S1wqZZi3-Lh_s-6Uw7p8vtgSwg"
-H "x-goog-acl: private" https://storage.googleapis.com/example-travel-maps/paris.jpg?acl

请求类似于如下示例:

PUT /paris.jpg?acl HTTP/1.1
Host: example-travel-maps.storage.googleapis.com
Date: Thu, 09 Oct 2014 23:14:59 GMT
Content-Length: 0
x-goog-acl: private
Authorization: Bearer ya29.AHES6ZRVmB7fkLtd1XTmq6mo0S1wqZZi3-Lh_s-6Uw7p8vtgSwg

empty entity body

设置默认对象 ACL

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

要查看和更改存储分区的默认对象 ACL,请执行以下操作:

Console

您无法使用 GCP Console 设置默认对象 ACL。请改为使用 gsutil。

gsutil

  1. 使用 gsutil defacl 检索默认对象 ACL:

    gsutil defacl get gs://[BUCKET_NAME]

  2. 使用 gsutil defacl chgsutil defacl set 修改默认对象 ACL。

    例如,以下命令可将 jane@gmail.com 添加到存储分区 example-travel-maps 的默认对象 ACL 中:

    gsutil defacl ch -u jane@gmail.com:READER gs://example-travel-maps

    您还可以从某个文件指定默认对象 ACL。如需了解更多信息,请参阅 gsutil defacl 帮助。

代码示例

C++

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

以下示例演示了如何为存储分区添加默认对象 ACL:

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

  if (!default_object_acl) {
    throw std::runtime_error(default_object_acl.status().message());
  }

  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 bucket_name, std::string 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 参考文档

以下示例演示了如何为存储分区添加默认对象 ACL:

private void AddBucketDefaultOwner(string bucketName, string userEmail)
{
    var storage = StorageClient.Create();
    var bucket = storage.GetBucket(bucketName, new GetBucketOptions()
    {
        Projection = Projection.Full
    });
    if (null == bucket.Acl)
    {
        bucket.Acl = new List<BucketAccessControl>();
    }
    if (null == bucket.DefaultObjectAcl)
    {
        bucket.DefaultObjectAcl = new List<ObjectAccessControl>();
    }
    bucket.DefaultObjectAcl.Add(new ObjectAccessControl()
    {
        Bucket = bucketName,
        Entity = $"user-{userEmail}",
        Role = "OWNER",
    });
    var updatedBucket = storage.UpdateBucket(bucket, new UpdateBucketOptions()
    {
        // Avoid race conditions.
        IfMetagenerationMatch = bucket.Metageneration,
    });
}

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

private void RemoveBucketDefaultOwner(string bucketName, string userEmail)
{
    var storage = StorageClient.Create();
    var bucket = storage.GetBucket(bucketName, new GetBucketOptions()
    {
        Projection = Projection.Full
    });
    if (null == bucket.DefaultObjectAcl)
        return;
    if (null == bucket.Acl)
    {
        bucket.Acl = new List<BucketAccessControl>();
    }
    bucket.DefaultObjectAcl = bucket.DefaultObjectAcl.Where((acl) =>
         !(acl.Entity == $"user-{userEmail}" && acl.Role == "OWNER")
        ).ToList();
    var updatedBucket = storage.UpdateBucket(bucket, new UpdateBucketOptions()
    {
        // Avoid race conditions.
        IfMetagenerationMatch = bucket.Metageneration,
    });
}

Go

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

以下示例演示了如何为存储分区添加默认对象 ACL:

func addDefaultBucketACL(client *storage.Client, bucket string) error {
	ctx := context.Background()

	acl := client.Bucket(bucket).DefaultObjectACL()
	if err := acl.Set(ctx, storage.AllAuthenticatedUsers, storage.RoleReader); err != nil {
		return err
	}
	return nil
}

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

func deleteDefaultBucketACL(client *storage.Client, bucket string) error {
	ctx := context.Background()

	acl := client.Bucket(bucket).DefaultObjectACL()
	if err := acl.Delete(ctx, storage.AllAuthenticatedUsers); err != nil {
		return err
	}
	return nil
}

Java

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

以下示例演示了如何为存储分区添加默认对象 ACL:

Acl acl =
    storage.createDefaultAcl(bucketName, Acl.of(User.ofAllAuthenticatedUsers(), Role.READER));

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

boolean deleted = storage.deleteDefaultAcl(bucketName, User.ofAllAuthenticatedUsers());
if (deleted) {
  // the acl entry was deleted
} else {
  // the acl entry was not found
}

Node.js

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

以下示例演示了如何为存储分区添加默认对象 ACL:

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

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

/**
 * TODO(developer): Uncomment the following line before running the sample.
 */
// const bucketName = 'Name of a bucket, e.g. my-bucket';
// const userEmail = 'Email of user to add, e.g. developer@company.com';

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

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

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

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

/**
 * TODO(developer): Uncomment the following line before running the sample.
 */
// const bucketName = 'Name of a bucket, e.g. my-bucket';
// const userEmail = 'Email of user to remove, e.g. developer@company.com';

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

PHP

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

以下示例演示了如何为存储分区添加默认对象 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.
 * @param string $entity The entity to update access controls for.
 * @param string $role The permissions to add for the specified entity. May
 *        be one of 'OWNER', 'READER', or 'WRITER'.
 * @param array $options
 *
 * @return void
 */
function add_bucket_default_acl($bucketName, $entity, $role, $options = [])
{
    $storage = new StorageClient();
    $bucket = $storage->bucket($bucketName);
    $acl = $bucket->defaultAcl();
    $acl->add($entity, $role, $options);
    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.
 * @param string $entity the name of the entity to remove from the ACL.
 * @param array $options
 *
 * @return void
 */
function delete_bucket_default_acl($bucketName, $entity, $options = [])
{
    $storage = new StorageClient();
    $bucket = $storage->bucket($bucketName);
    $acl = $bucket->defaultAcl();
    $acl->delete($entity, $options);
    printf('Deleted %s from gs://%s default ACL' . PHP_EOL, $entity, $bucketName);
}

Python

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

以下示例演示了如何为存储分区添加默认对象 ACL:

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."""
    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:

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."""
    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('Removed user {} from the default acl of bucket {}.'.format(
        user_email, bucket_name))

Ruby

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

以下示例演示了如何为存储分区添加默认对象 ACL:

# project_id  = "Your Google Cloud project ID"
# bucket_name = "Your Google Cloud Storage bucket name"
# email       = "Google Cloud Storage ACL Entity email"

require "google/cloud/storage"

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

bucket.default_acl.add_owner email

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

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

# project_id  = "Your Google Cloud project ID"
# bucket_name = "Your Google Cloud Storage bucket name"
# email       = "Google Cloud Storage ACL Entity email"

require "google/cloud/storage"

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

bucket.default_acl.delete email

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

JSON API

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

    curl -X GET -H "Authorization: Bearer [OAUTH2_TOKEN]" 
    https://www.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 [OAUTH2_TOKEN]" 
    https://www.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 [OAUTH2_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 [OAUTH2_TOKEN]" 
    http://storage.googleapis.com/[BUCKET_NAME]?defaultObjectAcl

    acls.xml 的一个示例:

    <AccessControlList>
    <Entries>
    <Entry>
    <Permission>FULL_CONTROL</Permission>
    <Scope type="GroupByEmail">
    <EmailAddress>travel-companions@googlegroups.com</EmailAddress>
    </Scope>
    </Entry>
    </Entries>
    </AccessControlList>

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

要将存储分区的默认对象 ACL 设为预定义的 ACL,请执行以下操作:

Console

您无法使用 GCP Console 设置默认对象 ACL。请改为使用 gsutil。

gsutil

使用 gsutil defacl 命令并搭配预定义 ACL 的名称。

例如,要将存储分区 example-travel-maps 的默认对象 ACL 设为 project-private,请运行以下命令:

gsutil defacl set project-private gs://example-travel-maps

JSON API

使用 PUT 请求和 predefinedAcl 参数。

例如:

curl -X PUT -H "Content-Length: 0" -H "Authorization: Bearer [OAUTH2_TOKEN]" 
https://www.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 [OAUTH2_TOKEN]" 
http://storage.googleapis.com/[BUCKET_NAME]?defaultObjectAcl

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

新创建的存储分区的默认对象 ACL 如下所示。将这些 ACL 与您的存储分区的默认对象 ACL 进行比较,以了解您的存储分区的默认对象 ACL 是否已被修改。

Console

您无法使用 GCP Console 处理默认对象 ACL。请改为使用 gsutil。

gsutil

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

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

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,请执行以下操作:

Console

  1. 转到 GCP Console 中的 Cloud Storage 浏览器。
    转到 Cloud Storage 浏览器

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

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

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

gsutil

使用 gsutil acl get 返回对象的 ACL。

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

gsutil acl get gs://example-travel-maps/paris.jpg

示例响应:

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

要返回存储分区的 ACL,请运行以下命令:

gsutil acl get gs://[BUCKET_NAME]

当 gsutil 通过 gsutil acl get 返回存储分区和对象的 ACL 时,它们同样使用 JSON 格式(您可以使用此格式设置 ACL)。JSON 格式的 ACL 使用 JSON API 属性名称,例如 entityrole

要详细了解如何解析输出或运行 gsutil help acls,请参阅 JSON API 语法。

代码示例

C++

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

以下示例演示了如何获取存储分区 ACL:

namespace gcs = google::cloud::storage;
using ::google::cloud::StatusOr;
[](gcs::Client client, std::string bucket_name) {
  StatusOr<std::vector<gcs::BucketAccessControl>> items =
      client.ListBucketAcl(bucket_name);

  if (!items) {
    throw std::runtime_error(items.status().message());
  }

  std::cout << "ACLs for bucket=" << bucket_name << "\n";
  for (gcs::BucketAccessControl const& acl : *items) {
    std::cout << acl.role() << ":" << acl.entity() << "\n";
  }
}

以下示例演示了如何获取对象 ACL:

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

  if (!items) {
    throw std::runtime_error(items.status().message());
  }

  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 参考文档

以下示例演示了如何获取存储分区 ACL:

private void PrintBucketAcl(string bucketName)
{
    var storage = StorageClient.Create();
    var bucket = storage.GetBucket(bucketName, new GetBucketOptions()
    {
        Projection = Projection.Full
    });
    if (bucket.Acl != null)
        foreach (var acl in bucket.Acl)
        {
            Console.WriteLine($"{acl.Role}:{acl.Entity}");
        }
}

以下示例演示了如何获取对象 ACL:

private void PrintObjectAcl(string bucketName, string objectName)
{
    var storage = StorageClient.Create();
    var storageObject = storage.GetObject(bucketName, objectName,
        new GetObjectOptions() { Projection = Projection.Full });
    if (storageObject.Acl != null)
    {
        foreach (var acl in storageObject.Acl)
        {
            Console.WriteLine($"{acl.Role}:{acl.Entity}");
        }
    }
}

Go

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

以下示例演示了如何获取存储分区 ACL:

func bucketACL(client *storage.Client, bucket string) error {
	ctx := context.Background()

	rules, err := client.Bucket(bucket).ACL().List(ctx)
	if err != nil {
		return err
	}
	for _, rule := range rules {
		fmt.Printf("ACL rule: %v\n", rule)
	}
	return nil
}

以下示例演示了如何获取对象 ACL:

func objectACL(client *storage.Client, bucket, object string) error {
	ctx := context.Background()

	rules, err := client.Bucket(bucket).Object(object).ACL().List(ctx)
	if err != nil {
		return err
	}
	for _, rule := range rules {
		fmt.Printf("ACL rule: %v\n", rule)
	}
	return nil
}

Java

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

以下示例演示了如何获取存储分区 ACL:

Acl acl = storage.getAcl(bucketName, User.ofAllAuthenticatedUsers());

以下示例演示了如何获取对象 ACL:

BlobId blobId = BlobId.of(bucketName, blobName, blobGeneration);
Acl acl = storage.getAcl(blobId, User.ofAllAuthenticatedUsers());

Node.js

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

以下示例演示了如何获取存储分区 ACL:

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

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

/**
 * TODO(developer): Uncomment the following line before running the sample.
 */
// const bucketName = 'Name of a bucket, e.g. my-bucket';

// Gets the ACL for the bucket
const [acls] = await storage.bucket(bucketName).acl.get();

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

以下示例演示了如何获取对象 ACL:

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

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

/**
 * TODO(developer): Uncomment the following line before running the sample.
 */
// const bucketName = 'Name of a bucket, e.g. my-bucket';
// const filename = 'File to access, e.g. file.txt';

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

PHP

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

以下示例演示了如何获取存储分区 ACL:

use Google\Cloud\Storage\StorageClient;

/**
 * Print all entities and roles for a bucket's ACL.
 *
 * @param string $bucketName the name of your Cloud Storage bucket.
 *
 * @return Google\Cloud\Storage\Acl the ACL for the Cloud Storage bucket.
 */
function get_bucket_acl($bucketName)
{
    $storage = new StorageClient();
    $bucket = $storage->bucket($bucketName);
    $acl = $bucket->acl();
    foreach ($acl->get() as $item) {
        printf('%s: %s' . PHP_EOL, $item['entity'], $item['role']);
    }
}

以下示例演示了如何获取对象 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.
 * @param string $objectName the name of your Cloud Storage object.
 *
 * @return void
 */
function get_object_acl($bucketName, $objectName)
{
    $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 参考文档

以下示例演示了如何获取存储分区 ACL:

def print_bucket_acl(bucket_name):
    """Prints out a bucket's access control list."""
    storage_client = storage.Client()
    bucket = storage_client.bucket(bucket_name)

    for entry in bucket.acl:
        print('{}: {}'.format(entry['role'], entry['entity']))

以下示例演示了如何获取对象 ACL:

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('{}: {}'.format(entry['role'], entry['entity']))

Ruby

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

以下示例演示了如何获取存储分区 ACL:

# project_id  = "Your Google Cloud project ID"
# bucket_name = "Your Google Cloud Storage bucket name"

require "google/cloud/storage"

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

puts "ACL for #{bucket_name}:"

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

bucket.acl.writers.each do |writer|
  puts "WRITER #{writer}"
end

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

以下示例演示了如何获取对象 ACL:

# project_id  = "Your Google Cloud project ID"
# bucket_name = "Your Google Cloud Storage 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 project_id: project_id
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

JSON API

  1. 确保您在存储分区或对象上具有 OWNER 权限。

  2. 使用 GET 请求检索存储分区或对象的 ACL。

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

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

curl -X GET -H "Authorization: Bearer ya29.AHES6ZRVmB7fkLtd1XTmq6mo0S1wqZZi3-Lh_s-6Uw7p8vtgSwg" 
https://www.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 ya29.AHES6ZRVmB7fkLtd1XTmq6mo0S1wqZZi3-Lh_s-6Uw7p8vtgSwg" 
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 条目。

更改 ACL

要更改现有对象或存储分区的 ACL,请执行以下操作:

Console

  1. 转到 GCP Console 中的 Cloud Storage 浏览器。
    转到 Cloud Storage 浏览器

  2. 导航到需要更改其 ACL 的对象。

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

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

以下示例显示了如何向 jane@gmail.com 用户授予对象 paris.jpgOWNER 权限以及向 gs-announce 群组成员授予该对象的 READER 权限:

在对象 paris.jpg 上设置 ACL。

gsutil

  1. 在文件中定义 ACL。

  2. 将 ACL 文件传递给 gsutil acl set,并指定要设置该 ACL 的对象。

例如,要将 acls.txt 文件中的 ACL 应用到存储分区 example-travel-maps 中名为 paris.jpg 的对象上,请运行以下命令:

gsutil acl set acl.txt gs://example-travel-maps/paris.jpg

acl.txt 的内容如下所示。这些 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"
}
]

您还可以使用单个授权操作为此对象设置相同的 ACL。例如,要向 jane@gmail.com 用户授予 READER 权限,请使用以下命令:

gsutil acl ch -u jane@gmail.com:READ gs://example-travel-maps/paris.jpg
.

代码示例

C++

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

以下示例演示了如何移除存储分区 ACL:

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

  if (!original_metadata) {
    throw std::runtime_error(original_metadata.status().message());
  }

  std::vector<gcs::BucketAccessControl> original_acl =
      original_metadata->acl();
  auto it = std::find_if(original_acl.begin(), original_acl.end(),
                         [entity](const gcs::BucketAccessControl& 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";
}

以下示例演示了如何移除对象 ACL:

namespace gcs = google::cloud::storage;
using ::google::cloud::StatusOr;
[](gcs::Client client, std::string bucket_name, std::string object_name,
   std::string entity) {
  StatusOr<gcs::ObjectMetadata> original_metadata = client.GetObjectMetadata(
      bucket_name, object_name, gcs::Projection::Full());

  if (!original_metadata) {
    throw std::runtime_error(original_metadata.status().message());
  }

  std::vector<gcs::ObjectAccessControl> original_acl =
      original_metadata->acl();
  auto it = std::find_if(original_acl.begin(), original_acl.end(),
                         [entity](const gcs::ObjectAccessControl& 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 参考文档

以下示例演示了如何移除存储分区 ACL:

private void RemoveBucketOwner(string bucketName, string userEmail)
{
    var storage = StorageClient.Create();
    var bucket = storage.GetBucket(bucketName, new GetBucketOptions()
    {
        Projection = Projection.Full
    });
    if (null == bucket.Acl)
        return;
    bucket.Acl = bucket.Acl.Where((acl) =>
        !(acl.Entity == $"user-{userEmail}" && acl.Role == "OWNER")
        ).ToList();
    var updatedBucket = storage.UpdateBucket(bucket, new UpdateBucketOptions()
    {
        // Avoid race conditions.
        IfMetagenerationMatch = bucket.Metageneration,
    });
}

以下示例演示了如何移除对象 ACL:

private void RemoveObjectOwner(string bucketName, string objectName,
    string userEmail)
{
    var storage = StorageClient.Create();
    var storageObject = storage.GetObject(bucketName, objectName,
        new GetObjectOptions() { Projection = Projection.Full });
    if (null == storageObject.Acl)
        return;
    storageObject.Acl = storageObject.Acl.Where((acl) =>
        !(acl.Entity == $"user-{userEmail}" && acl.Role == "OWNER")
        ).ToList();
    var updatedObject = storage.UpdateObject(storageObject, new UpdateObjectOptions()
    {
        // Avoid race conditions.
        IfMetagenerationMatch = storageObject.Metageneration,
    });
}

Go

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

以下示例演示了如何移除存储分区 ACL:

func deleteBucketACL(client *storage.Client, bucket string) error {
	ctx := context.Background()

	acl := client.Bucket(bucket).ACL()
	if err := acl.Delete(ctx, storage.AllAuthenticatedUsers); err != nil {
		return err
	}
	return nil
}

以下示例演示了如何移除对象 ACL:

func deleteObjectACL(client *storage.Client, bucket, object string) error {
	ctx := context.Background()

	acl := client.Bucket(bucket).Object(object).ACL()
	if err := acl.Delete(ctx, storage.AllAuthenticatedUsers); err != nil {
		return err
	}
	return nil
}

Java

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

以下示例演示了如何移除存储分区 ACL:

boolean deleted = storage.deleteAcl(bucketName, User.ofAllAuthenticatedUsers());
if (deleted) {
  // the acl entry was deleted
} else {
  // the acl entry was not found
}

以下示例演示了如何移除对象 ACL:

BlobId blobId = BlobId.of(bucketName, blobName, blobGeneration);
boolean deleted = storage.deleteAcl(blobId, User.ofAllAuthenticatedUsers());
if (deleted) {
  // the acl entry was deleted
} else {
  // the acl entry was not found
}

Node.js

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

以下示例演示了如何移除存储分区 ACL:

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

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

/**
 * TODO(developer): Uncomment the following line before running the sample.
 */
// const bucketName = 'Name of a bucket, e.g. my-bucket';
// const userEmail = 'Email of user to remove, e.g. developer@company.com';

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

以下示例演示了如何移除对象 ACL:

async function removeFileOwner(bucketName, filename, userEmail) {
  // Imports the Google Cloud client library
  const {Storage} = require('@google-cloud/storage');

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

  /**
   * TODO(developer): Uncomment the following line before running the sample.
   */
  // const bucketName = 'Name of a bucket, e.g. my-bucket';
  // const filename = 'Name of file to access, e.g. file.txt';
  // const userEmail = 'Email of user to remove, e.g. developer@company.com';

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

PHP

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

以下示例演示了如何移除存储分区 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.
 * @param string $entity the name of the entity to remove from the ACL.
 * @param array $options
 *
 * @return void
 */
function delete_bucket_acl($bucketName, $entity, $options = [])
{
    $storage = new StorageClient();
    $bucket = $storage->bucket($bucketName);
    $acl = $bucket->acl();
    $acl->delete($entity, $options);
    printf('Deleted %s from gs://%s ACL' . PHP_EOL, $entity, $bucketName);
}

以下示例演示了如何移除对象 ACL:

use Google\Cloud\Storage\StorageClient;

/**
 * Delete an entity from an object's ACL.
 *
 * @param string $bucketName the name of your Cloud Storage bucket.
 * @param string $objectName the name of your Cloud Storage object.
 * @param string $entity The entity to update access controls for.
 * @param array $options
 *
 * @return void
 */
function delete_object_acl($bucketName, $objectName, $entity, $options = [])
{
    $storage = new StorageClient();
    $bucket = $storage->bucket($bucketName);
    $object = $bucket->object($objectName);
    $acl = $object->acl();
    $acl->delete($entity, $options);
    printf('Deleted %s from gs://%s/%s ACL' . PHP_EOL, $entity, $bucketName, $objectName);
}

Python

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

以下示例演示了如何移除存储分区 ACL:

def remove_bucket_owner(bucket_name, user_email):
    """Removes a user from the access control list of the given bucket."""
    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('Removed user {} from bucket {}.'.format(
        user_email, bucket_name))

以下示例演示了如何移除对象 ACL:

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."""
    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('Removed user {} from blob {} in bucket {}.'.format(
        user_email, blob_name, bucket_name))

Ruby

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

以下示例演示了如何移除存储分区 ACL:

# project_id  = "Your Google Cloud project ID"
# bucket_name = "Your Google Cloud Storage bucket name"
# email       = "Google Cloud Storage ACL Entity email"

require "google/cloud/storage"

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

bucket.acl.delete email

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

以下示例演示了如何移除对象 ACL:

# project_id  = "Your Google Cloud project ID"
# bucket_name = "Your Google Cloud Storage 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 project_id: project_id
bucket  = storage.bucket bucket_name
file    = bucket.file file_name

file.acl.delete email

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

JSON API

  1. 在 JSON 文件中定义 ACL。

  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 ya29.AHES6ZRVmB7fkLtd1XTmq6mo0S1wqZZi3-Lh_s-6Uw7p8vtgSwg"
https://www.googleapis.com/storage/v1/b/example-travel-maps/o/paris.jpg

如果 ACL 向项目 867489160491 的所有者以及用户 jane@gmail.com 授予 OWNER 权限,以及向 gs-announce 群组成员授予 READER 权限,则请求如下所示:

PATCH /storage/v1/b/example-travel-maps/o/paris.jpg HTTP/1.1
Host: www.googleapis.com
Content-Type: application/json
Authorization: Bearer ya29.AHES6ZRVmB7fkLtd1XTmq6mo0S1wqZZi3-Lh_s-6Uw7p8vtgSwg
Content-Length: 597
Date: Wed, 08 Oct 2014 22:37:58 GMT
{
"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"
}
]
}

XML API

  1. 在 XML 文档中定义 ACL。

  2. 使用 acl 查询字符串参数和相应的 XML 文档发送 PUT Object 请求。

以下 cURL 命令将文档 acls.xml 中的 XML 负载应用到存储分区 example-travel-maps 中名为 paris.jpg 的对象:

curl -X PUT --data-binary @acls.xml 
-H "Authorization: Bearer ya29.AHES6ZRVmB7fkLtd1XTmq6mo0S1wqZZi3-Lh_s-6Uw7p8vtgSwg"
https://storage.googleapis.com/example-travel-maps/paris.jpg?acl

如果 ACL 向 jane@gmail.com 用户授予 FULL_CONTROL 权限,以及向 gs-announce 群组成员授予 READ 权限,则请求如下所示:

PUT /paris.jpg?acl HTTP/1.1
Host: example-travel-maps.storage.googleapis.com
Date: Sat, 20 Feb 2010 08:31:08 GMT
Content-Length: 589
Content-Type=application/xml
Authorization: Bearer ya29.AHES6ZRVmB7fkLtd1XTmq6mo0S1wqZZi3-Lh_s-6Uw7p8vtgSwg

<?xml version='1.0' encoding='utf-8'?>
<AccessControlList>
<Owner>
<ID>84fac329bceSAMPLE777d5d22b8SAMPLE77d85ac2SAMPLE2dfcf7c4adf34da46</ID>
</Owner>
<Entries>
<Entry>
<Permission>FULL_CONTROL</Permission>
<Scope type="UserById">
  <ID>84fac329bceSAMPLE777d5d22b8SAMPLE77d85ac2SAMPLE2dfcf7c4adf34da46</ID>
</Scope>
</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>

此页内容是否有用?请给出您的反馈和评价:

发送以下问题的反馈:

此网页
Cloud Storage
需要帮助?请访问我们的支持页面