建立及管理存取控制清單 (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 的權限會套用到值區內所有物件。不過對於值區內所有物件共用的存取權,您還是要使用 Cloud IAM,這樣可以減少細部控制的管理工作。

一文。

是否需要設定 ACL?

是否需要設定 ACL 取決於您想要授予值區或物件的權限。有時使用預設 ACL 建立的值區和物件,可能就已經包含您要提供給值區或物件的權限。

請按照下列指示說明,判斷您是否需要設定 ACL。

針對值區:

主控台

使用預先定義的 project-privateACL 建立新值區。如果您的值區需要使用其他權限,請設定 ACL

gsutil

新增的值區將套用 project-private 權限。如果您的值區需要使用其他權限,請設定 ACL

JSON API

根據預設,新增的值區將套用 project-private 權限。如果您的值區需要使用其他權限,請設定 ACL

XML API

新增的值區將套用 project-private 權限。如果您的值區需要使用其他權限,請設定 ACL

如上文所述,每個值區都有一個預設的物件 ACL,如果值區內沒有預先定義的 ACL (比如說您使用的是 JSON API) 或您已透過要求指定 ACL,這時系統就會對這些值區內的所有物件套用預設 ACL。詳情請參閱「預設物件 ACL」。

針對物件:

主控台

已上傳物件和值區物件採用同樣的 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。

  • 您先前必須有過提出 HTTP 要求的經驗,才能使用 API 指定 ACL。您可以使用自己喜歡的工具或應用程式傳送 HTTP 要求。在本文的例子中,我們使用的是 cURL 工具;您可以從 OAuth 2.0 Playground 取得授權憑證,以便在這些 cURL 例子中使用。

設定 ACL

視您用來設定和取得 ACL 的工具或 ACP 而定,ACL 語法也會有所不同。ACL 語法看起來雖然各不相同,但其中都會包含相同的 ACL 資訊:對範圍授予權限的項目。

主控台

  1. 前往 GCP Console 的 Cloud Storage 瀏覽器。
    前往 Cloud Storage 瀏覽器

  2. 找出您想要修改 ACL 的物件。

  3. 在下拉式選單中,為物件選擇 [Edit Permissions] (編輯權限)

    這時畫面上會出現類似下圖的權限對話方塊:

    這個螢幕擷圖顯示具有四個項目的 ACL:

    • 在第一個項目中,這個專案 (專案編號為 867489140601) 的所有擁有者都會獲得該物件的「Owner」存取權限。
    • 在第二個項目中,這個專案 (專案編號為 867489140601) 的所有編輯者也會獲得該物件的「Owner」存取權限。
    • 在第三個項目中,這個專案 (專案編號為 867489140601) 的所有檢視者都會獲得該物件的「Reader」存取權限。
    • 在第四個項目中,上傳物件的使用者會獲得該物件的「Owner」存取權限。請注意,物件上傳者一律設為「Owner」且無法移除。
  4. 按一下 [新增項目]。

  5. 選擇要授予權限給哪類型的「Entity」(實體)

    「Entity」(實體) 欄用來指定接受權限的項目類型 (例如使用者或群組),如需支援的「Entity」(實體) 值清單,請參閱存取控制範圍

  6. 在「Name」(名稱) 欄中輸入值。

    「Name」(名稱) 欄可指定使用者、群組或其他實體類型。如需支援的「Name」(名稱) 值清單,請參閱存取控制範圍

    「Entity」(實體) 和「Name」(名稱) 兩者並用即可定義權限的適用對象。

  7. 在欄中選取「Access」(存取權)

    「Access」(存取權) 欄可定義您要指定給物件的權限。如需支援的「Access」(存取權) 值清單,請參閱存取控制權限

  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

建立值區時,您可以在 insert 要求中指定 acl[] 屬性;針對現有值區,請在 patchupdate 要求中指定 acl[] 屬性。

建立物件時,您可以在要求主體或是 insert 要求的 predefinedAcl 查詢參數中指定 acl[] 屬性;針對現有物件,請在 patchupdate 要求的 predefinedAcl 查詢參數中指定 acl[] 屬性。

如需值區和物件 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 要求建立值區後,請透過另一個 PUT 值區要求搭配 ?acl 參數變更值區 ACL。

  • 使用 PUT Object 要求上傳物件後,請透過另一個 PUT 要求搭配 ?acl 參數或 x-googl-acl 要求標頭變更 ACL。

針對 XML API 請使用下列 ACL 語法。

元素 說明
AccessControlList EntriesOwner 元素的容器。
Owner DisplayNameID 元素的容器。物件不需要這個元素,因為物件一律由上傳者所擁有。這個元素的使用時機是當您在遷移的情況下使用 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 指定權限項目時,權限授予對象的 ID。
EmailAddress 以電子郵件指定權限項目時,權限授予對象的電子郵件 ID。
Domain 以網域指定權限項目時,權限授予對象的網域 ID。
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> 元素中提供任何值,而 Cloud Storage 會記住這些值,直到 ACL 遭移除或覆寫後才會刪除。使用像是 Google Cloud Storage ID 這些很難辨別的 ID 時,這個方法非常實用。

  2. UserByEmailGroupByEmail 範圍包含公開的 Google 個人資料時

    如果您使用上述其中一個範圍但並未提供 <Name> 元素,Cloud Storage 會檢查與電子郵件地址相關聯的使用者或 Google 群組是否有公開的 Google 個人資料。如果有,Cloud Storage 將自動在 <Name> 元素中填入找到的公開名稱。

套用預先定義的 ACL

如果不想按照上文一次一個項目地指定整個 ACL,您可以利用預先定義的 ACL 自動套用多個針對特定情況自訂的項目。您可以使用 gsutil、JSON API 或 XML API 將預先定義的 ACL 套用到值區或物件。

針對新物件

在物件上傳期間將預先定義的 ACL 套用至物件:

主控台

您無法使用 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

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 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,就可以採取這種做法。

主控台

您無法使用 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

使用 predefinedAcl 查詢字串參數,然後在 patch 要求中指定空的 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 要求中搭配 acl 查詢字串參數使用 x-goog-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:

主控台

您無法使用 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。舉例來說,下列要求將使用 defacls.json 中指定的 ACL 取代值區 example-travel-maps 的預設物件 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:

主控台

您無法使用 GCP Console 設定預設物件 ACL,請改用 gsutil。

gsutil

使用採用預先定義 ACL 名稱的 gsutil defacl 指令。

舉例來說,如要將值區 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 是否已修改。

主控台

您無法使用 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:

主控台

  1. 前往 GCP Console 的 Cloud Storage 瀏覽器。
    前往 Cloud Storage 瀏覽器

  2. 找出您想要查看的 ACL 所屬的物件。

  3. 在下拉式選單中,為物件選擇 [Edit permissions] (編輯權限)

    這時畫面上會出現列有物件權限的權限對話方塊。

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 時,這些都會採用您可用來設定 ACL 的 JSON 格式。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:

主控台

  1. 前往 GCP Console 的 Cloud Storage 瀏覽器。
    前往 Cloud Storage 瀏覽器

  2. 找出您想要變更的 ACL 所屬的物件。

  3. 在下拉式選單中,為物件選擇 [Edit permissions] (編輯權限)

    這時畫面上會出現列有物件權限的權限對話方塊。

以下範例說明如何在物件 paris.jpg 上授予 jane@gmail.com 使用者 OWNER 權限以及授予 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. 在檔案中定義 ACL。

  2. 隨 ACL 檔案傳送 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
需要協助嗎?請前往我們的支援網頁