建立及管理存取控制清單 (ACL)

總覽

這個頁面說明如何使用存取控制清單 (ACL) 控制值區和物件的存取權。ACL 這種機制可讓您定義有權存取值區和物件的對象和存取層級。

如要進一步瞭解是否應使用 ACL 控制資源存取權,請參閱 ACL 總覽

必要的角色

如要取得建立及管理 ACL 所需的權限,請要求管理員在值區中授予您儲存空間管理員 (roles/storage.admin) IAM 角色。該值區包含您要建立及管理 ACL 的物件。

這個預先定義的角色具備建立及管理 ACL 所需的權限。如要查看確切的必要權限,請展開「必要權限」部分:

所需權限

  • storage.buckets.get
  • storage.buckets.list
    • 只有使用 Google Cloud 控制台執行這個頁面的工作時,才需要這項權限。
  • storage.buckets.setIamPolicy
  • storage.buckets.update
  • storage.objects.get
  • storage.objects.getIamPolicy
  • storage.objects.setIamPolicy
  • storage.objects.update

您也可以透過自訂角色取得這些權限。

如要瞭解如何授予值區角色,請參閱「搭配值區使用 IAM」。

設定或修改 ACL

控制台

  1. 前往 Google Cloud 控制台的 Cloud Storage 瀏覽器。
    前往 Cloud Storage 瀏覽器

  2. 在值區清單中,找出包含要修改 ACL 物件的值區,然後按一下該值區的名稱。

  3. 按一下要設定或修改 ACL 的物件名稱。

  4. 按一下「編輯存取權」

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

  5. 按一下「+ 新增項目」

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

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

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

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

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

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

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

  9. 按一下 [儲存]

如要瞭解如何透過 Google Cloud 控制台取得 Cloud Storage 作業失敗的詳細錯誤資訊,請參閱「疑難排解」。

指令列

如要新增、修改或移除物件的個別授權,請使用 objects update 指令並加上相關旗標:

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

其中:

  • BUCKET_NAME 是包含要修改物件的值區名稱。例如:example-travel-maps

  • OBJECT_NAME 是要套用修改內容的物件名稱。例如:paris.jpg

  • FLAG 是下列其中一項:

    • --add-acl-grant,以及要新增或修改的授權。例如:--add-acl-grant=entity=user-jeffersonloveshiking@gmail.com,role=READER

    • --remove-acl-grant,以及要移除存取權的實體。例如:--remove-acl-grant=user-jeffersonloveshiking@gmail.com

如要取代物件的所有 ACL,請執行下列操作:

  1. 在 JSON 或 YAML 格式的檔案中定義 ACL。

    舉例來說,下列 ACL 會將物件 paris.jpgOWNER 權限授予專案 867489160491 擁有者和使用者 jeffersonloveshiking@gmail.com,並將 paris.jpgREADER 權限授予 gs-announce 群組成員:

    [
    {
      "entity": "project-owners-867489160491",
      "role": "OWNER",
      "projectTeam": {
        "projectNumber": "867489160491",
        "team": "owners"
      },
    },
    {
      "entity": "user-jeffersonloveshiking@gmail.com",
      "email": "jeffersonloveshiking@gmail.com",
      "role": "OWNER"
    },
    {
      "entity": "group-gs-announce@googlegroups.com",
      "email": "gs-announce@googlegroups.com",
      "role": "READER"
    }
    ]
    
  2. 使用加上 --acl-file 旗標的 objects update 指令:

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

    其中:

    • BUCKET_NAME 是包含要套用 ACL 的物件的值區名稱。例如:example-travel-maps

    • OBJECT_NAME 是要套用 ACL 的物件名稱。例如:paris.jpg

    • FILE_LOCATION 是包含您定義 ACL 的檔案本機路徑。例如:Desktop/acls.json

用戶端程式庫

C++

詳情請參閱 Cloud Storage C++ API 參考說明文件

如要驗證 Cloud Storage,請設定應用程式預設憑證。 詳情請參閱「設定用戶端程式庫的驗證機制」。

下例示範如何新增 ACL 到物件:

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

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

下例示範如何從物件移除 ACL:

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

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

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

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

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

C#

詳情請參閱 Cloud Storage C# API 參考說明文件

如要驗證 Cloud Storage,請設定應用程式預設憑證。 詳情請參閱「設定用戶端程式庫的驗證機制」。

下例示範如何新增 ACL 到物件:


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

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

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

下例示範如何從物件移除 ACL:


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

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

Go

詳情請參閱 Cloud Storage Go API 參考說明文件

如要驗證 Cloud Storage,請設定應用程式預設憑證。 詳情請參閱「設定用戶端程式庫的驗證機制」。

下例示範如何新增 ACL 到物件:

import (
	"context"
	"fmt"

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

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

	ctx := context.Background()
	client, err := storage.NewClient(ctx)
	if err != nil {
		return fmt.Errorf("storage.NewClient: %w", err)
	}
	defer client.Close()

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

下例示範如何從物件移除 ACL:

import (
	"context"
	"fmt"

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

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

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

Java

詳情請參閱 Cloud Storage Java API 參考說明文件

如要驗證 Cloud Storage,請設定應用程式預設憑證。 詳情請參閱「設定用戶端程式庫的驗證機制」。

下例示範如何新增 ACL 到物件:


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

public class AddBlobOwner {

  public static void addBlobOwner(
      String projectId, String bucketName, String userEmail, String blobName) {
    // The ID of your GCP project
    // String projectId = "your-project-id";

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

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

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

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

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

下例示範如何從物件移除 ACL:


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

public class RemoveBlobOwner {

  public static void removeBlobOwner(
      String projectId, String bucketName, String userEmail, String blobName) {
    // The ID of your GCP project
    // String projectId = "your-project-id";

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

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

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

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

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

Node.js

詳情請參閱 Cloud Storage Node.js API 參考說明文件

如要驗證 Cloud Storage,請設定應用程式預設憑證。 詳情請參閱「設定用戶端程式庫的驗證機制」。

下例示範如何新增 ACL 到物件:

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

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

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

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

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

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

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

addFileOwner().catch(console.error);

下例示範如何從物件移除 ACL:

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

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

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

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

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

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

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

removeFileOwner().catch(console.error);

PHP

詳情請參閱 Cloud Storage PHP API 參考說明文件

如要驗證 Cloud Storage,請設定應用程式預設憑證。 詳情請參閱「設定用戶端程式庫的驗證機制」。

下例示範如何新增 ACL 到物件:

use Google\Cloud\Storage\StorageClient;

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

下例示範如何從物件移除 ACL:

use Google\Cloud\Storage\StorageClient;

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

Python

詳情請參閱 Cloud Storage Python API 參考說明文件

如要驗證 Cloud Storage,請設定應用程式預設憑證。 詳情請參閱「設定用戶端程式庫的驗證機制」。

下例示範如何新增 ACL 到物件:

from google.cloud import storage


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

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

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

    # You can also use `group`, `domain`, `all_authenticated` and `all` to
    # grant access to different types of entities. You can also use
    # `grant_read` or `grant_write` to grant different roles.
    blob.acl.user(user_email).grant_owner()
    blob.acl.save()

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

下例示範如何從物件移除 ACL:

from google.cloud import storage


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

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

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

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

Ruby

詳情請參閱 Cloud Storage Ruby API 參考說明文件

如要驗證 Cloud Storage,請設定應用程式預設憑證。 詳情請參閱「設定用戶端程式庫的驗證機制」。

下例示範如何新增 ACL 到物件:

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

require "google/cloud/storage"

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

file.acl.add_owner email

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

下例示範如何從物件移除 ACL:

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

require "google/cloud/storage"

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

file.acl.delete email

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

REST API

JSON API

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

如需物件 ACL 屬性的定義,請參閱 ObjectAccessControls 資源。

  1. 在檔案中定義 ACL。

    舉例來說,如果 ACL 對專案 867489160491 的擁有者和使用者 jeffersonloveshiking@gmail.com 授予 OWNER 權限,並對 gs-announce 群組的成員授予 READER 權限,這時您可能會有名為 acls.json 的檔案,內容如下:

    {
    "acl": [
      {
        "entity": "project-owners-867489160491",
        "role": "OWNER",
        "projectTeam": {
          "projectNumber": "867489160491",
          "team": "owners"
        }
      },
      {
        "entity": "user-jeffersonloveshiking@gmail.com",
        "role": "OWNER",
        "email": "jeffersonloveshiking@gmail.com"
      },
      {
        "entity": "group-gs-announce@googlegroups.com",
        "role": "READER",
        "email": "gs-announce@googlegroups.com"
      }
    ]
    }
    
  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 $(gcloud auth print-access-token)" \
    https://storage.googleapis.com/storage/v1/b/example-travel-maps/o/paris.jpg

XML API

XML API 中,您要使用 XML 格式的 ACL。您必須在要求主體附加 XML 文件,才能變更值區和物件 ACL。取得值區和物件 ACL 時,系統會傳回 XML 文件。XML 文件中將列出個別值區或物件 ACL 項目。

  • 使用 PUT Bucket 要求建立值區後,請透過另一個 PUT 值區要求搭配 ?acl 參數變更值區 ACL。

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

舉例來說,以下 curl 指令會將文件 acls.xml 中的 XML 酬載套用至值區 example-travel-maps 中名為 paris.jpg 的物件:

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

針對 XML 文件請使用下列 ACL 語法:

元素 說明
AccessControlList EntriesOwner 元素的容器。
Owner DisplayNameID 元素的容器。物件不需要這個元素,因為物件一律由上傳者所擁有。這個元素的使用時機是當您在遷移的情況下使用 Amazon S3 ACL 語法時。

Amazon Simple Storage Service™ 和 Amazon S3™ 是 Amazon.com, Inc. 或其關聯企業在美國和/或其他國家/地區的商標。
ID 值區擁有者的 Cloud Storage ID。
DisplayName 尚未實作。該值一律為空字串。
Entries 零或更多 Entry 元素的容器。
Entry ScopePermission 元素的容器。Entry 只能包含一個 Scope 和一個 Permission 元素。
Scope IDEmailAddressDomain 元素的容器,用來定義 ACL 範圍。這個元素必須有一個包含以下任一個值的 type 屬性:UserByIDUserByEmailGroupByIDGroupByEmailGroupByDomainAllUsersAllAuthenticatedUsers
ID 以 ID 指定權限項目時,權限授予對象的 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="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>jeffersonloveshiking@gmail.com</EmailAddress>
        <Name>Jefferson</Name>
      </Scope>
      <Permission>FULL_CONTROL</Permission>
    </Entry>
    <Entry>
      <Scope type="AllUsers"/>
      <Permission>READ</Permission>
    </Entry>
    <Entry>
      <Scope type="AllAuthenticatedUsers"/>
      <Permission>READ</Permission>
    </Entry>
  </Entries>
</AccessControlList>

在 ACL XML 中設定 Name 元素

從值區或物件擷取 ACL 時,您可能會注意到部分項目附加了額外的 <Name> 元素。舉例來說,您可能會看到如下所示的項目:

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

遇到下列兩種情況時,系統會在這些選用的 <Name> 元素中填入值:

  1. 值區或物件的 ACL 包含做為元素的 <Name>

    您設定 ACL 時可能會在 ACL 項目中加入 <Name> 元素。您可以在 <Name> 元素中提供任何值,而 Cloud Storage 會記住這些值,直到 ACL 遭移除或取代後才會刪除。使用很難辨別的 ID 時,這個方法非常實用。

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

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

套用預先定義的 ACL

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

針對新物件

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

控制台

您無法使用 Google Cloud console 套用預先定義的 ACL,請改用 gcloud storage

指令列

使用 gcloud storage cp 指令並加上 --predefined-acl 旗標:

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

舉例來說,假設要在上傳物件 paris.jpg 到值區 example-travel-maps 時套用預先定義的 ACL bucketOwnerRead,方式如下:

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

REST API

JSON API

insert 要求中使用 predefinedAcl 查詢字串參數,套用預先定義的 ACL。

舉例來說,假設要在上傳物件 paris.jpg 到值區 example-travel-maps 時套用預先定義的 ACL bucketOwnerRead,方式如下:

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

XML API

Put Object 要求中使用 x-goog-acl 標頭,套用預先定義的 ACL。

舉例來說,假設要在上傳物件 paris.jpg 到值區 example-travel-maps 時套用預先定義的 ACL bucket-owner-read,方式如下:

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

針對現有值區或物件

您也可以對現有值區或物件套用預先定義的 ACL。當您想要從某個預先定義的 ACL 改用另一個,或想要上傳自訂 ACL 到預先定義的 ACL,就可以採取這種做法。

控制台

您無法使用 Google Cloud console 套用預先定義的 ACL,請改用 gcloud storage

指令列

使用加上 --predefined-acl 旗標的 objects update 指令:

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

舉例來說,假設要將預先定義的 ACL private 套用到值區 example-travel-maps 中的物件 paris.jpg,方式如下:

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

REST API

JSON API

使用 predefinedAcl 查詢字串參數,然後在 patch 要求中指定空的 acl 屬性,套用預先定義的 ACL。

舉例來說,假設要將預先定義的 ACL private 套用到值區 example-travel-maps 中的物件 paris.jpg,方式如下:

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

XML API

Put Object 要求中搭配 acl 查詢字串參數使用 x-goog-acl 標頭,但請勿在要求中納入 XML 文件。

舉例來說,假設要將預先定義的 ACL private 套用到值區 example-travel-maps 中的物件 paris.jpg,方式如下:

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

設定預設物件 ACL

如果不想每次新建物件時都要設定 ACL,您可以為值區設定預設物件 ACL。完成之後,新增到該值區的所有新物件如果沒有明確套用的 ACL,系統將套用預設的 ACL。舉例來說,您可能會想指定只讓特定群組的使用者存取特定值區中的大部分物件。您可以變更預設物件 ACL,然後新增物件到該值區。這些新增的物件將自動套用您指定的預設物件 ACL;不過,您還是可以針對特定物件使用不同的 ACL,這樣一來,這些物件就不會套用預設的 ACL。

查看及變更值區的預設物件 ACL:

控制台

您無法使用 Google Cloud 主控台設定預設物件 ACL,請改用 gcloud storage

指令列

  1. 使用 buckets describe 指令搭配 --format 旗標,擷取值區的預設物件 ACL:

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

    其中 BUCKET_NAME 是您要查看預設物件 ACL 的值區名稱。例如:my-bucket

  2. 使用 buckets update 指令搭配所需旗標,修改值區的預設物件 ACL:

    gcloud storage buckets update gs://BUCKET_NAME FLAG

    其中:

    • BUCKET_NAME 是要修改預設物件 ACL 的值區名稱。例如:my-bucket

    • FLAG 是下列其中一項:

      • --add-default-object-acl-grant,以及您要新增至值區整體預設物件 ACL 的授權。

      • ,以及定義值區新預設物件 ACL 的本機檔案路徑。--default-object-acl-file

      • --predefined-default-object-acl,以及您要用來取代值區現有預設物件 ACL 的預先定義物件 ACL 名稱。

      • --remove-default-object-acl-grant,以及要從值區的整體預設物件 ACL 中移除的實體。

用戶端程式庫

C++

詳情請參閱 Cloud Storage C++ API 參考說明文件

如要驗證 Cloud Storage,請設定應用程式預設憑證。 詳情請參閱「設定用戶端程式庫的驗證機制」。

下例示範如何新增預設物件 ACL 到值區:

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

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

下例示範如何從值區刪除預設物件 ACL:

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

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

C#

詳情請參閱 Cloud Storage C# API 參考說明文件

如要驗證 Cloud Storage,請設定應用程式預設憑證。 詳情請參閱「設定用戶端程式庫的驗證機制」。

下例示範如何列印值區的預設物件 ACL:


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

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

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

        return bucket.DefaultObjectAcl;
    }
}

下例示範如何新增預設物件 ACL 到值區:


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

public class AddBucketDefaultOwnerSample
{
    public Bucket AddBucketDefaultOwner(
        string bucketName = "your-unique-bucket-name",
        string userEmail = "dev@iam.gserviceaccount.com")
    {
        var storage = StorageClient.Create();
        var bucket = storage.GetBucket(bucketName, new GetBucketOptions { Projection = Projection.Full });

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

下例示範如何從值區刪除預設物件 ACL:


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

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

Go

詳情請參閱 Cloud Storage Go API 參考說明文件

如要驗證 Cloud Storage,請設定應用程式預設憑證。 詳情請參閱「設定用戶端程式庫的驗證機制」。

下例示範如何新增預設物件 ACL 到值區:

import (
	"context"
	"fmt"

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

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

	ctx := context.Background()
	client, err := storage.NewClient(ctx)
	if err != nil {
		return fmt.Errorf("storage.NewClient: %w", err)
	}
	defer client.Close()

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

下例示範如何從值區刪除預設物件 ACL:

import (
	"context"
	"fmt"

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

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

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

Java

詳情請參閱 Cloud Storage Java API 參考說明文件

如要驗證 Cloud Storage,請設定應用程式預設憑證。 詳情請參閱「設定用戶端程式庫的驗證機制」。

下例示範如何新增預設物件 ACL 到值區:


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

public class AddBucketDefaultOwner {

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

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

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

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

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

下例示範如何從值區刪除預設物件 ACL:


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

public class RemoveBucketDefaultOwner {

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

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

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

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

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

Node.js

詳情請參閱 Cloud Storage Node.js API 參考說明文件

如要驗證 Cloud Storage,請設定應用程式預設憑證。 詳情請參閱「設定用戶端程式庫的驗證機制」。

下例示範如何新增預設物件 ACL 到值區:

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

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

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

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

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

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

addBucketDefaultOwner().catch(console.error);

下例示範如何從值區刪除預設物件 ACL:

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

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

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

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

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

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

removeBucketDefaultOwner().catch(console.error);

PHP

詳情請參閱 Cloud Storage PHP API 參考說明文件

如要驗證 Cloud Storage,請設定應用程式預設憑證。 詳情請參閱「設定用戶端程式庫的驗證機制」。

下例示範如何新增預設物件 ACL 到值區:

use Google\Cloud\Storage\StorageClient;

/**
 * Add an entity and role to a bucket's default ACL.
 *
 * @param string $bucketName The name of your Cloud Storage bucket.
 *        (e.g. 'my-bucket')
 * @param string $entity The entity for which to update access controls.
 *        (e.g. 'user-example@domain.com')
 * @param string $role The permissions to add for the specified entity.
 *        (e.g. 'OWNER')
 */
function add_bucket_default_acl(string $bucketName, string $entity, string $role): void
{
    $storage = new StorageClient();
    $bucket = $storage->bucket($bucketName);
    $acl = $bucket->defaultAcl();
    $acl->add($entity, $role);
    printf('Added %s (%s) to gs://%s default ACL' . PHP_EOL, $entity, $role, $bucketName);
}

下例示範如何從值區刪除預設物件 ACL:

use Google\Cloud\Storage\StorageClient;

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

Python

詳情請參閱 Cloud Storage Python API 參考說明文件

如要驗證 Cloud Storage,請設定應用程式預設憑證。 詳情請參閱「設定用戶端程式庫的驗證機制」。

下例示範如何新增預設物件 ACL 到值區:

from google.cloud import storage


def add_bucket_default_owner(bucket_name, user_email):
    """Adds a user as an owner in the given bucket's default object access
    control list."""
    # bucket_name = "your-bucket-name"
    # user_email = "name@example.com"

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

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

    # You can also use `group`, `domain`, `all_authenticated` and `all` to
    # grant access to different types of entities. You can also use
    # `grant_read` or `grant_write` to grant different roles.
    bucket.default_object_acl.user(user_email).grant_owner()
    bucket.default_object_acl.save()

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

下例示範如何從值區刪除預設物件 ACL:

from google.cloud import storage


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

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

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

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

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

Ruby

詳情請參閱 Cloud Storage Ruby API 參考說明文件

如要驗證 Cloud Storage,請設定應用程式預設憑證。 詳情請參閱「設定用戶端程式庫的驗證機制」。

下例示範如何新增預設物件 ACL 到值區:

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

require "google/cloud/storage"

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

bucket.default_acl.add_owner email

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

下例示範如何從值區刪除預設物件 ACL:

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

require "google/cloud/storage"

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

bucket.default_acl.delete email

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

REST API

JSON API

  1. 使用 GET 要求擷取預設物件 ACL。例如:

    curl -X GET -H "Authorization: Bearer $(gcloud auth print-access-token)" \
        https://storage.googleapis.com/storage/v1/b/BUCKET_NAME?projection=full
    
  2. 使用 patch 要求取代預設物件 ACL。舉例來說,下列要求將使用 defacls.json 中指定的 ACL 取代值區 example-travel-maps 的預設物件 ACL:

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

    defacls.json 的範例:

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

XML API

  1. 使用範圍限定在您值區的 GET 要求和 ?defaultObjectAcl 參數來擷取預設物件 ACL。例如:

    curl -X GET -H "Authorization: Bearer $(gcloud auth print-access-token)" \
        https://storage.googleapis.com/BUCKET_NAME?defaultObjectAcl
    
  2. 使用範圍限定在您值區的 PUT 要求搭配 ?defaultObjectAcl 參數,將預設物件 ACL 取代為 acls.xml 中指定的 ACL。例如:

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

    acls.xml 的範例:

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

ACL 語法將在「設定 ACL」一文中進一步說明。您也可以將預先定義的 ACL 指定為預設的物件 ACL。

將值區的預設物件 ACL 設為預先定義的 ACL:

控制台

您無法使用 Google Cloud 主控台設定預設物件 ACL,請改用 gcloud storage

指令列

使用加上 --predefined-default-object-acl 旗標的 buckets update 指令:

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

其中:

  • BUCKET_NAME 是要修改預設物件 ACL 的值區名稱。例如:my-bucket

  • PREDEFINED_ACL 是有效預先定義 ACL 的名稱。例如:projectPrivate

REST API

JSON API

使用 PUT 要求和 predefinedAcl 參數。

例如:

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

XML API

使用範圍限定在您值區的 PUT 要求搭配 ?defaultObjectAcl 參數和 x-goog-acl 標頭。

例如:

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

新建值區的預設物件 ACL:

如果您未在要求中指定自己的預設物件 ACL,系統會自動將下列預設物件 ACL 套用至新建值區。如要查看值區的預設物件 ACL 是否已變更,請比較值區目前的預設物件 ACL 與下列範例。

控制台

您無法使用 Google Cloud 控制台處理預設物件 ACL,請改用 gcloud storage

指令列

本例的專案 ID 是「123412341234」,您的專案 ID 可能會不同。

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

REST API

JSON API

本例的專案 ID 是「123412341234」,您的專案 ID 可能會不同。

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

XML API

本例的專案角色 ID 開頭是「00b4903a97...」,您的專案 ID 可能會不同。

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

請注意,新建值區的預設物件 ACL 相當於預先定義的 projectPrivate ACL。

擷取 ACL

取得現有資源的 ACL:

控制台

  1. 前往 Google Cloud 控制台的 Cloud Storage 瀏覽器。
    前往 Cloud Storage 瀏覽器

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

  3. 在下拉式選單中,為物件選擇「編輯存取權」

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

如要瞭解如何透過 Google Cloud 控制台取得 Cloud Storage 作業失敗的詳細錯誤資訊,請參閱「疑難排解」。

指令列

  1. 使用 objects describe 指令並加上 --format 標記,即可擷取物件的 ACL:

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

    其中:

    • BUCKET_NAME 是值區名稱,其中包含您要查看 ACL 的物件。例如:my-bucket

    • OBJECT_NAME 是您要查看 ACL 的物件名稱。例如:paris.jpg

用戶端程式庫

C++

詳情請參閱 Cloud Storage C++ API 參考說明文件

如要驗證 Cloud Storage,請設定應用程式預設憑證。 詳情請參閱「設定用戶端程式庫的驗證機制」。

下例示範如何取得物件 ACL:

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

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

C#

詳情請參閱 Cloud Storage C# API 參考說明文件

如要驗證 Cloud Storage,請設定應用程式預設憑證。 詳情請參閱「設定用戶端程式庫的驗證機制」。

下例示範如何取得物件 ACL:


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

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

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

        return storageObject.Acl;
    }
}

Go

詳情請參閱 Cloud Storage Go API 參考說明文件

如要驗證 Cloud Storage,請設定應用程式預設憑證。 詳情請參閱「設定用戶端程式庫的驗證機制」。

下例示範如何取得物件 ACL:

import (
	"context"
	"fmt"
	"io"

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

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

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

Java

詳情請參閱 Cloud Storage Java API 參考說明文件

如要驗證 Cloud Storage,請設定應用程式預設憑證。 詳情請參閱「設定用戶端程式庫的驗證機制」。

下例示範如何取得物件 ACL:


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

public class PrintBlobAcl {

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

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

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

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

    for (Acl acl : blobAcls) {

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

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

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

Node.js

詳情請參閱 Cloud Storage Node.js API 參考說明文件

如要驗證 Cloud Storage,請設定應用程式預設憑證。 詳情請參閱「設定用戶端程式庫的驗證機制」。

下例示範如何取得物件 ACL:

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

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

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

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

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

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

printFileAcl().catch(console.error);

PHP

詳情請參閱 Cloud Storage PHP API 參考說明文件

如要驗證 Cloud Storage,請設定應用程式預設憑證。 詳情請參閱「設定用戶端程式庫的驗證機制」。

下例示範如何取得物件 ACL:

use Google\Cloud\Storage\StorageClient;

/**
 * Print all entities and roles for an object's ACL.
 *
 * @param string $bucketName The name of your Cloud Storage bucket.
 *        (e.g. 'my-bucket')
 * @param string $objectName The name of your Cloud Storage object.
 *        (e.g. 'my-object')
 */
function get_object_acl(string $bucketName, string $objectName): void
{
    $storage = new StorageClient();
    $bucket = $storage->bucket($bucketName);
    $object = $bucket->object($objectName);
    $acl = $object->acl();
    foreach ($acl->get() as $item) {
        printf('%s: %s' . PHP_EOL, $item['entity'], $item['role']);
    }
}

Python

詳情請參閱 Cloud Storage Python API 參考說明文件

如要驗證 Cloud Storage,請設定應用程式預設憑證。 詳情請參閱「設定用戶端程式庫的驗證機制」。

下例示範如何取得物件 ACL:

from google.cloud import storage


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

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

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

Ruby

詳情請參閱 Cloud Storage Ruby API 參考說明文件

如要驗證 Cloud Storage,請設定應用程式預設憑證。 詳情請參閱「設定用戶端程式庫的驗證機制」。

下例示範如何取得物件 ACL:

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

require "google/cloud/storage"

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

puts "ACL for #{file_name} in #{bucket_name}:"

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

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

REST API

JSON API

  1. 確認您有物件的 OWNER 權限。

  2. 使用 GET 要求擷取物件 ACL。

    物件 ACL 將以 JSON 格式傳回,並附加到回應主體。

舉例來說,如要傳回值區 example-travel-maps 中物件 paris.jpg 的 ACL:

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

這時畫面上會出現類似下方的回應:

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

您也可以使用 objectAccessControls 資源 GET 方法傳回物件 ACL 中的個別項目。

XML API

  1. 確定您有值區或物件的 FULL_CONTROL 權限。

  2. 使用 GET Object 要求中的 acl 查詢字串參數,擷取值區或物件 ACL。

ACL 以 XML 形式描述,並附加到回應主體。

舉例來說,如要傳回值區 example-travel-maps 中物件 paris.jpg 的 ACL:

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

這時畫面上會出現類似下方的回應:

<?xml version="1.0" encoding="UTF-8"?>
<AccessControlList>
  <Owner>
    <ID>84fac329bceSAMPLE777d5d22b8SAMPLE77d85ac2SAMPLE2dfcf7c4adf34da46</ID>
    <Name>Owner Name</Name>
  </Owner>
  <Entries>
    <Entry>
      <Scope type="UserById">
        <ID>84fac329bceSAMPLE777d5d22b8SAMPLE77d85ac2SAMPLE2dfcf7c4adf34da46</ID>
        <Name>Name</Name>
      </Scope>
      <Permission>FULL_CONTROL</Permission>
    </Entry>
    <Entry>
      <Scope type="UserByEmail">
        <EmailAddress>jeffersonloveshiking@gmail.com</EmailAddress>
        <Name>Jefferson</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 項目。

後續步驟