公開您的資料

本頁說明如何將您持有的物件設為可供公開網際網路上的所有人讀取,以及如何從值區中移除公開存取權。如要瞭解如何存取已設為公開的資料,請參閱存取公開資料一文。

當物件公開共用時,只要物件為公開,有該物件 URI 的任何使用者就都可以存取物件。

必要的角色

如要取得將物件設為可公開讀取所需的權限,請要求管理員為您授予下列角色,以便存取內含要公開資料的 bucket:

  • 如何將值區中的所有物件設為可公開讀取:Storage 管理員 (roles/storage.admin)

  • 如何將個別物件設成可公開讀取:Storage 物件管理員 (roles/storage.objectAdmin)

    • 如果您打算使用 Google Cloud 控制台,則需要「Storage Admin」(儲存空間管理員) (roles/storage.admin) 角色,而非「Storage Object Admin」(儲存空間物件管理員) 角色。
  • 如要移除 bucket 中所有物件的公開存取權,請使用 Storage 管理員 (roles/storage.admin) 角色。

這些角色具備將物件設為公開所需的權限。如要查看確切的必要權限,請展開「必要權限」部分:

所需權限

  • storage.buckets.get
  • storage.buckets.getIamPolicy
  • storage.buckets.setIamPolicy
  • storage.buckets.update
  • storage.objects.get
  • storage.objects.getIamPolicy
  • storage.objects.setIamPolicy
  • storage.objects.update

如要使用Google Cloud 控制台執行本頁的工作,您只需要下列權限:

  • storage.buckets.list
  • storage.objects.list

您或許還可透過其他預先定義的角色自訂角色取得這些權限。

如需如何授予值區角色的操作說明,請參閱「搭配值區使用 IAM」。

將 bucket 中的所有物件設為可公開讀取

如要讓公開網路上所有使用者都能讀取 bucket 中的所有物件,請將 Storage 物件檢視者 (roles/storage.objectViewer) 角色授予主體 allUsers

控制台

  1. 在 Google Cloud 控制台,前往「Cloud Storage bucket」頁面。

    前往「Buckets」(值區) 頁面

  2. 在值區清單中,找到您要設為公開的值區名稱,然後點選這個名稱。

  3. 選取靠近頁面上方的 [Permissions] (權限) 分頁標籤。

  4. 在「權限」部分中,按一下「授予存取權」按鈕

    系統會隨即顯示「授予存取權」對話方塊。

  5. 在「New principals」(新增主體) 欄位中輸入 allUsers

  6. 在「請選擇角色」下拉式選單中,在篩選方塊中輸入 Storage Object Viewer,然後從篩選結果中選取「Storage 物件檢視者」

  7. 按一下 [儲存]

  8. 按一下「Allow public access」(允許公開存取)

授予公開存取權後,「public access」(公開存取權) 欄中會顯示各個物件的「Copy URL」(複製網址) 按鈕。按一下這個按鈕即可取得物件的公開網址。公開網址與直接在物件上按下滑鼠右鍵取得的連結不同。這兩個連結都可用來存取物件,但使用公開網址就不需要登入使用者帳戶。詳情請參閱「要求端點」。

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

如要瞭解如何解決機構政策錯誤和權限錯誤,請參閱「排解公開資料問題」。

指令列

  1. In the Google Cloud console, activate Cloud Shell.

    Activate Cloud Shell

    At the bottom of the Google Cloud console, a Cloud Shell session starts and displays a command-line prompt. Cloud Shell is a shell environment with the Google Cloud CLI already installed and with values already set for your current project. It can take a few seconds for the session to initialize.

  2. 在開發環境中執行 buckets add-iam-policy-binding 指令:

    gcloud storage buckets add-iam-policy-binding gs://BUCKET_NAME --member=allUsers --role=roles/storage.objectViewer

    其中 BUCKET_NAME 是要將物件設為公開的值區名稱。例如:my-bucket

用戶端程式庫

C++

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

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

namespace gcs = ::google::cloud::storage;
using ::google::cloud::StatusOr;
[](gcs::Client client, std::string const& bucket_name) {
  auto current_policy = client.GetNativeBucketIamPolicy(
      bucket_name, gcs::RequestedPolicyVersion(3));
  if (!current_policy) throw std::move(current_policy).status();

  current_policy->set_version(3);
  current_policy->bindings().emplace_back(
      gcs::NativeIamBinding("roles/storage.objectViewer", {"allUsers"}));

  auto updated =
      client.SetNativeBucketIamPolicy(bucket_name, *current_policy);
  if (!updated) throw std::move(updated).status();

  std::cout << "Policy successfully updated: " << *updated << "\n";
}

C#

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

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


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

public class MakeBucketPublicSample
{
    public void MakeBucketPublic(string bucketName = "your-unique-bucket-name")
    {
        var storage = StorageClient.Create();

        Policy policy = storage.GetBucketIamPolicy(bucketName);

        policy.Bindings.Add(new Policy.BindingsData
        {
            Role = "roles/storage.objectViewer",
            Members = new List<string> { "allUsers" }
        });

        storage.SetBucketIamPolicy(bucketName, policy);
        Console.WriteLine(bucketName + " is now public ");
    }
}

Go

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

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

import (
	"context"
	"fmt"
	"io"

	"cloud.google.com/go/iam"
	"cloud.google.com/go/iam/apiv1/iampb"
	"cloud.google.com/go/storage"
)

// setBucketPublicIAM makes all objects in a bucket publicly readable.
func setBucketPublicIAM(w io.Writer, bucketName string) error {
	// bucketName := "bucket-name"
	ctx := context.Background()
	client, err := storage.NewClient(ctx)
	if err != nil {
		return fmt.Errorf("storage.NewClient: %w", err)
	}
	defer client.Close()

	policy, err := client.Bucket(bucketName).IAM().V3().Policy(ctx)
	if err != nil {
		return fmt.Errorf("Bucket(%q).IAM().V3().Policy: %w", bucketName, err)
	}
	role := "roles/storage.objectViewer"
	policy.Bindings = append(policy.Bindings, &iampb.Binding{
		Role:    role,
		Members: []string{iam.AllUsers},
	})
	if err := client.Bucket(bucketName).IAM().V3().SetPolicy(ctx, policy); err != nil {
		return fmt.Errorf("Bucket(%q).IAM().SetPolicy: %w", bucketName, err)
	}
	fmt.Fprintf(w, "Bucket %v is now publicly readable\n", bucketName)
	return nil
}

Java

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

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

import com.google.cloud.Identity;
import com.google.cloud.Policy;
import com.google.cloud.storage.Storage;
import com.google.cloud.storage.StorageOptions;
import com.google.cloud.storage.StorageRoles;

public class MakeBucketPublic {
  public static void makeBucketPublic(String projectId, String bucketName) {
    // The ID of your GCP project
    // String projectId = "your-project-id";

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

    Storage storage = StorageOptions.newBuilder().setProjectId(projectId).build().getService();
    Policy originalPolicy = storage.getIamPolicy(bucketName);
    storage.setIamPolicy(
        bucketName,
        originalPolicy.toBuilder()
            .addIdentity(StorageRoles.objectViewer(), Identity.allUsers()) // All users can view
            .build());

    System.out.println("Bucket " + bucketName + " is now publicly readable");
  }
}

Node.js

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

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

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

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

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

async function makeBucketPublic() {
  await storage.bucket(bucketName).makePublic();

  console.log(`Bucket ${bucketName} is now publicly readable`);
}

makeBucketPublic().catch(console.error);

PHP

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

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

use Google\Cloud\Storage\StorageClient;

/**
 * Update the specified bucket's IAM configuration to make it publicly accessible.
 *
 * @param string $bucketName The name of your Cloud Storage bucket.
 *        (e.g. 'my-bucket')
 */
function set_bucket_public_iam(string $bucketName): void
{
    $storage = new StorageClient();
    $bucket = $storage->bucket($bucketName);

    $policy = $bucket->iam()->policy(['requestedPolicyVersion' => 3]);
    $policy['version'] = 3;

    $role = 'roles/storage.objectViewer';
    $members = ['allUsers'];

    $policy['bindings'][] = [
        'role' => $role,
        'members' => $members
    ];

    $bucket->iam()->setPolicy($policy);

    printf('Bucket %s is now public', $bucketName);
}

Python

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

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

from typing import List

from google.cloud import storage


def set_bucket_public_iam(
    bucket_name: str = "your-bucket-name",
    members: List[str] = ["allUsers"],
):
    """Set a public IAM Policy to bucket"""
    # bucket_name = "your-bucket-name"

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

    policy = bucket.get_iam_policy(requested_policy_version=3)
    policy.bindings.append(
        {"role": "roles/storage.objectViewer", "members": members}
    )

    bucket.set_iam_policy(policy)

    print(f"Bucket {bucket.name} is now publicly readable")

Ruby

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

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

def set_bucket_public_iam bucket_name:
  # The ID of your GCS bucket
  # bucket_name = "your-unique-bucket-name"

  require "google/cloud/storage"

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

  bucket.policy do |p|
    p.add "roles/storage.objectViewer", "allUsers"
  end

  puts "Bucket #{bucket_name} is now publicly readable"
end

Terraform

您可以使用 Terraform 資源,將 bucket 中的所有物件設為公開。

# Make bucket public
resource "google_storage_bucket_iam_member" "member" {
  provider = google
  bucket   = google_storage_bucket.default.name
  role     = "roles/storage.objectViewer"
  member   = "allUsers"
}

REST API

JSON API

  1. 安裝並初始化 gcloud CLI,以便為 Authorization 標頭產生存取權杖。

  2. 建立包含下列資訊的 JSON 檔案:

    {
      "bindings":[
        {
          "role": "roles/storage.objectViewer",
          "members":["allUsers"]
        }
      ]
    }
  3. 使用 cURL 透過 PUT Bucket 要求呼叫 JSON API

    curl -X PUT --data-binary @JSON_FILE_NAME \
      -H "Authorization: Bearer $(gcloud auth print-access-token)" \
      -H "Content-Type: application/json" \
      "https://storage.googleapis.com/storage/v1/b/BUCKET_NAME/iam"

    其中:

    • JSON_FILE_NAME 是您在步驟 2 建立的檔案路徑。
    • BUCKET_NAME 是要將物件設為公開的值區名稱。例如:my-bucket

XML API

XML API 不支援將值區中的所有物件設為可公開讀取,使用 Google Cloud 控制台或 gcloud storage

將 bucket 的部分內容設為可公開讀取

使用代管資料夾控管物件存取權,這些物件的名稱前置字串與代管資料夾的名稱相符。舉例來說,名為 my-folder 的代管資料夾可用於控管名為 my-folder/cats.jpgmy-folder/dogs.jpg 的物件存取權。

如要讓這類物件可供公開存取,請先建立受管理資料夾,然後在資料夾上設定 IAM 政策,授予 allUsers Storage 物件檢視者 (roles/storage.objectViewer) 角色:

控制台

  1. 在 Google Cloud 控制台,前往「Cloud Storage bucket」頁面。

    前往「Buckets」(值區) 頁面

  2. 按一下包含要設為公開物件的值區名稱。

  3. 按照下列步驟建立資料夾:

    1. 按一下「建立資料夾」按鈕。

    2. 輸入資料夾的名稱。資料夾轉換為受管理資料夾後,名稱開頭為這個名稱的物件,就會受到資料夾中設定的 IAM 角色限制。

    3. 點選「建立」

  4. 請按照下列步驟,將資料夾轉換為受管理資料夾:

    1. 在顯示 bucket 內容的窗格中,找出您建立的資料夾名稱,然後按一下「More options」(更多選項) 圖示

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

    3. 在顯示的視窗中按一下 [Enable] (啟用)。

  5. 在資料夾中新增 IAM 政策,授予 allUsers Storage 物件檢視者 (roles/storage.objectViewer) 角色,步驟如下:

    1. 如果受管理資料夾的「權限」窗格尚未開啟,請依序點選受管理資料夾的「更多選項」圖示 和「編輯存取權」

    2. 在「Permissions」(權限) 窗格中,按一下 「Add principal」(新增主體) 按鈕。

    3. 在「New principals」(新增主體) 欄位中輸入 allUsers

    4. 在「請選擇角色」下拉式選單中,在篩選方塊中輸入 Storage Object Viewer,然後從篩選結果中選取「Storage 物件檢視者」

    5. 按一下 [儲存]

    6. 按一下「Allow public access」(允許公開存取)

授予公開存取權後,「公開存取權」欄中會出現各個適用物件的「複製網址」按鈕。按一下這個按鈕即可取得物件的公開網址。公開網址與直接在物件上按下滑鼠右鍵取得的連結不同。這兩個連結都可用來存取物件,但使用公開網址就不需要登入使用者帳戶。詳情請參閱「要求端點」。

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

如要瞭解如何解決機構政策錯誤和權限錯誤,請參閱「排解公開資料問題」。

指令列

  1. In the Google Cloud console, activate Cloud Shell.

    Activate Cloud Shell

    At the bottom of the Google Cloud console, a Cloud Shell session starts and displays a command-line prompt. Cloud Shell is a shell environment with the Google Cloud CLI already installed and with values already set for your current project. It can take a few seconds for the session to initialize.

  2. 在開發環境中,使用 gcloud storage managed-folders create 指令建立受管理資料夾:

    gcloud storage managed-folders create gs://BUCKET_NAME/MANAGED_FOLDER_NAME/

    其中:

    • BUCKET_NAME 是您要建立受管理資料夾的值區名稱。例如:my-bucket

    • MANAGED_FOLDER_NAME 是要建立的受管理資料夾名稱。例如:my-managed-folder

  3. 在開發環境中,使用 gcloud storage managed-folders add-iam-policy-binding 指令,將 allUsers 新增至受管理資料夾的 IAM 政策:

    gcloud storage managed-folders add-iam-policy-binding gs://BUCKET_NAME/MANAGED_FOLDER_NAME --member=allUsers --role=roles/storage.objectViewer

    其中:

    • BUCKET_NAME 是包含您要新增 IAM 政策的代管資料夾的值區名稱。例如:my-bucket
    • MANAGED_FOLDER_NAME 是要新增公開存取權的受管理資料夾名稱。例如:my-managed-folder

REST API

JSON API

  1. 安裝並初始化 gcloud CLI,以便為 Authorization 標頭產生存取權杖。

  2. 建立包含下列資訊的 JSON 檔案:

    {
      "name": "MANAGED_FOLDER_NAME"
    }

    其中 MANAGED_FOLDER_NAME 是要建立的受管理資料夾名稱。例如:my-managed-folder

  3. 使用 cURL 透過 Insert ManagedFolder 要求呼叫 JSON API

    curl -X POST --data-binary @JSON_FILE_NAME \
      -H "Authorization: Bearer $(gcloud auth print-access-token)" \
      -H "Content-Type: application/json" \
      "https://storage.googleapis.com/storage/v1/b/BUCKET_NAME/managedFolders"

    其中:

    • JSON_FILE_NAME 是您在上一個步驟中建立的檔案路徑。
    • BUCKET_NAME 是您要建立受管理資料夾的值區名稱。例如:my-bucket
  4. 建立包含下列資訊的 JSON 檔案:

    {
      "bindings":[
        {
          "role": "roles/storage.objectViewer",
          "members":["allUsers"]
        }
      ]
    }
  5. 使用 cURL 透過 setIamPolicy ManagedFolder 要求呼叫 JSON API

    curl -X PUT --data-binary @JSON_FILE_NAME \
      -H "Authorization: Bearer $(gcloud auth print-access-token)" \
      -H "Content-Type: application/json" \
      "https://storage.googleapis.com/storage/v1/b/BUCKET_NAME/managedFolders/MANAGED_FOLDER_NAME/iam"

    其中:

    • JSON_FILE_NAME 是您在上一個步驟中建立的檔案路徑。
    • BUCKET_NAME 是包含您要新增 IAM 政策的代管資料夾的值區名稱。例如:my-bucket
    • MANAGED_FOLDER_NAME 是您要新增 IAM 政策的受管理資料夾名稱。例如:my-managed-folder

XML API

XML API 不支援使用受管理資料夾。請使用其他工具 (例如 Google Cloud 控制台),或使用 Set Object ACL 要求,針對個別物件設定 ACL。以下是 ACL 檔案範例,可授予 allUsers 物件存取權:

<AccessControlList>
  <Entries>
    <Entry>
      <Scope type="AllUsers"/>
      <Permission>READ</Permission>
    </Entry>
  </Entries>
</AccessControlList>

移除值區中所有物件的公開存取權

如要移除值區中所有物件的公開存取權,請移除授予 allUsers「Storage 物件檢視者」(roles/storage.objectViewer) 角色的 IAM 政策:

控制台

  1. 在 Google Cloud 控制台,前往「Cloud Storage bucket」頁面。

    前往「Buckets」(值區) 頁面

  2. 在 bucket 清單中,點選要移除公開存取權的 bucket 名稱。

  3. 選取 [權限] 分頁標籤。

    套用至值區的身分與存取權管理政策會顯示在「權限」部分。

  4. 在「View by principals」(依主體檢視) 分頁中,選取要移除的allUsers主體核取方塊。

  5. 按一下「移除存取權」按鈕。

  6. 在隨即出現的重疊視窗中,按一下「確認」

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

指令列

  1. In the Google Cloud console, activate Cloud Shell.

    Activate Cloud Shell

    At the bottom of the Google Cloud console, a Cloud Shell session starts and displays a command-line prompt. Cloud Shell is a shell environment with the Google Cloud CLI already installed and with values already set for your current project. It can take a few seconds for the session to initialize.

  2. 在開發環境中執行 buckets remove-iam-policy-binding 指令

gcloud storage buckets remove-iam-policy-binding  gs://BUCKET_NAME --member=allUsers --role=roles/storage.objectViewer

其中 BUCKET_NAME 是要撤銷存取權的值區名稱。例如:my-bucket

REST API

JSON

  1. 安裝並初始化 gcloud CLI,以便為 Authorization 標頭產生存取權杖。

  2. 取得已套用至 bucket 的現有政策,方法是使用 cURL 透過 GET getIamPolicy 要求呼叫 JSON API

    curl -X GET \
    -H "Authorization: Bearer $(gcloud auth print-access-token)" \
    "https://storage.googleapis.com/storage/v1/b/BUCKET_NAME/iam"

    其中 BUCKET_NAME 是您要查看其 IAM 政策的值區名稱。例如:my-bucket

  3. 建立 JSON 檔案,其中須包含您在上個步驟擷取的政策,並編輯該檔案,從政策中移除 allUsers 主體的繫結。

  4. 使用 cURL 來透過 PUT setIamPolicy 要求呼叫呼叫 JSON API

    curl -X PUT --data-binary @JSON_FILE_NAME \
    -H "Authorization: Bearer $(gcloud auth print-access-token)" \
    -H "Content-Type: application/json" \
    "https://storage.googleapis.com/storage/v1/b/BUCKET_NAME/iam"

    其中:

    • JSON_FILE_NAME 是您在步驟 3 建立的檔案路徑。

    • BUCKET_NAME 是您要移除存取權的值區名稱。例如:my-bucket

後續步驟