使用禁止公開存取功能

總覽

本頁面說明如何使用禁止公開存取值區設定和禁止公開存取組織政策限制。您可以使用禁止公開存取,對值區和物件的公開存取權增設限制。

事前準備

在 Cloud Storage 中使用禁止公開存取功能前,請確認您具備必要的 IAM 角色,並查看強制執行禁止公開存取功能的考量因素。

取得必要角色

如要在專案、資料夾或機構層級管理禁止公開存取的機構政策,請要求管理員授予您機構的「機構政策管理員」(roles/orgpolicy.policyAdmin) 角色。這個預先定義的角色包含在專案、資料夾或機構層級管理公開存取預防功能所需的權限。如要進一步瞭解這個角色包含的權限,請參閱機構管理員角色的詳細資訊

如要管理值區的禁止公開存取設定,請要求管理員授予您該值區的儲存空間管理員 (roles/storage.admin) 角色。這個角色具備管理值區禁止公開存取功能所需的權限。如要查看確切的必要權限,請展開「必要權限」部分:

所需權限

  • storage.buckets.update
  • storage.buckets.setIamPolicy

如要進一步瞭解 Storage 管理員角色的其他權限,請參閱 Storage 管理員角色的詳細資訊

審查注意事項

開始前,建議您確認禁止公開存取權不會導致任何工作流程中斷。詳情請參閱「在現有資源上強制執行時的考量事項」。

使用值區設定

本節說明如何對個別值區強制執行及移除禁止公開存取的功能,以及如何檢查個別值區的狀態。

設定禁止公開存取

如要變更個別值區的公開存取預防設定,請按照下列步驟操作:

控制台

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

    前往「Buckets」(值區) 頁面

  2. 在值區清單中,點選要強制執行或移除「禁止公開存取」的值區名稱。

  3. 在「Bucket details」(值區詳細資料) 頁面中,按一下「Permissions」(權限) 分頁標籤。

  4. 在「Public access」(公開存取權) 資訊卡中,點按「Prevent public access」(禁止公開存取) 強制執行這項功能,或按一下「Allow public access」(允許公開存取) 移除這項功能。

  5. 按一下「確認」。

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

指令列

使用加上適當旗標的 gcloud storage buckets update 指令:

gcloud storage buckets update gs://BUCKET_NAME FLAG

其中:

  • BUCKET_NAME 是相關值區的名稱。例如:my-bucket

  • FLAG--public-access-prevention 以啟用不可公開存取功能,或是 --no-public-access-prevention 以停用該功能。

如果成功,回應會類似以下範例:

Updating gs://my-bucket/...
  Completed 1  

用戶端程式庫

C++

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

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

以下範例會在值區中強制禁止公開存取:

namespace gcs = ::google::cloud::storage;
using ::google::cloud::StatusOr;
[](gcs::Client client, std::string const& bucket_name) {
  gcs::BucketIamConfiguration configuration;
  configuration.public_access_prevention =
      gcs::PublicAccessPreventionEnforced();
  StatusOr<gcs::BucketMetadata> updated = client.PatchBucket(
      bucket_name, gcs::BucketMetadataPatchBuilder().SetIamConfiguration(
                       std::move(configuration)));
  if (!updated) throw std::move(updated).status();

  std::cout << "Public Access Prevention is set to 'enforced' for "
            << updated->name() << "\n";
}

下例示範如何將值區的公開存取限制設為 inherited

namespace gcs = ::google::cloud::storage;
using ::google::cloud::StatusOr;
[](gcs::Client client, std::string const& bucket_name) {
  gcs::BucketIamConfiguration configuration;
  configuration.public_access_prevention =
      gcs::PublicAccessPreventionInherited();
  auto updated = client.PatchBucket(
      bucket_name, gcs::BucketMetadataPatchBuilder().SetIamConfiguration(
                       std::move(configuration)));
  if (!updated) throw std::move(updated).status();

  std::cout << "Public Access Prevention is set to 'inherited' for "
            << updated->name() << "\n";
}

C#

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

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

以下範例會在值區中強制禁止公開存取:


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

public class SetPublicAccessPreventionEnforcedSample
{
    public Bucket SetPublicAccessPreventionEnforced(string bucketName = "your-unique-bucket-name")
    {
        var storage = StorageClient.Create();
        var bucket = storage.GetBucket(bucketName);

        // Set public access prevention to "enforced" for the bucket.
        bucket.IamConfiguration.PublicAccessPrevention = "enforced";
        bucket = storage.UpdateBucket(bucket);

        Console.WriteLine($"Public access prevention is 'enforced' for {bucketName}.");
        return bucket;
    }
}

下例示範如何將值區的公開存取限制設為 inherited


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

public class SetPublicAccessPreventionInheritedSample
{
    public Bucket SetPublicAccessPreventionInherited(string bucketName = "your-unique-bucket-name")
    {
        var storage = StorageClient.Create();
        var bucket = storage.GetBucket(bucketName);

        // Sets public access prevention to "inherited" for the bucket.
        bucket.IamConfiguration.PublicAccessPrevention = "inherited";
        bucket = storage.UpdateBucket(bucket);

        Console.WriteLine($"Public access prevention is 'inherited' for {bucketName}.");
        return bucket;
    }
}

Go

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

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

以下範例會在值區上強制禁止公開存取:

import (
	"context"
	"fmt"
	"io"
	"time"

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

// setPublicAccessPreventionEnforced sets public access prevention to
// "enforced" for the bucket.
func setPublicAccessPreventionEnforced(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()

	ctx, cancel := context.WithTimeout(ctx, time.Second*10)
	defer cancel()

	bucket := client.Bucket(bucketName)
	setPublicAccessPrevention := storage.BucketAttrsToUpdate{
		PublicAccessPrevention: storage.PublicAccessPreventionEnforced,
	}
	if _, err := bucket.Update(ctx, setPublicAccessPrevention); err != nil {
		return fmt.Errorf("Bucket(%q).Update: %w", bucketName, err)
	}
	fmt.Fprintf(w, "Public access prevention is 'enforced' for %v", bucketName)
	return nil
}

下例示範如何將值區的公開存取限制設為 inherited

import (
	"context"
	"fmt"
	"io"
	"time"

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

// setPublicAccessPreventionInherited sets public access prevention to
// "inherited" for the bucket.
func setPublicAccessPreventionInherited(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()

	ctx, cancel := context.WithTimeout(ctx, time.Second*10)
	defer cancel()

	bucket := client.Bucket(bucketName)
	setPublicAccessPrevention := storage.BucketAttrsToUpdate{
		PublicAccessPrevention: storage.PublicAccessPreventionInherited,
	}
	if _, err := bucket.Update(ctx, setPublicAccessPrevention); err != nil {
		return fmt.Errorf("Bucket(%q).Update: %w", bucketName, err)
	}
	fmt.Fprintf(w, "Public access prevention is 'inherited' for %v", bucketName)
	return nil
}

Java

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

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

以下範例會在值區中強制禁止公開存取:

import com.google.cloud.storage.Bucket;
import com.google.cloud.storage.BucketInfo;
import com.google.cloud.storage.Storage;
import com.google.cloud.storage.StorageOptions;

public class SetPublicAccessPreventionEnforced {
  public static void setPublicAccessPreventionEnforced(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();
    Bucket bucket = storage.get(bucketName);

    // Enforces public access prevention for the bucket
    bucket.toBuilder()
        .setIamConfiguration(
            BucketInfo.IamConfiguration.newBuilder()
                .setPublicAccessPrevention(BucketInfo.PublicAccessPrevention.ENFORCED)
                .build())
        .build()
        .update();

    System.out.println("Public access prevention is set to enforced for " + bucketName);
  }
}

下例示範如何將值區的公開存取限制設為 inherited

import com.google.cloud.storage.Bucket;
import com.google.cloud.storage.BucketInfo;
import com.google.cloud.storage.Storage;
import com.google.cloud.storage.StorageOptions;

public class SetPublicAccessPreventionInherited {
  public static void setPublicAccessPreventionInherited(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();
    Bucket bucket = storage.get(bucketName);

    // Sets public access prevention to 'inherited' for the bucket
    bucket.toBuilder()
        .setIamConfiguration(
            BucketInfo.IamConfiguration.newBuilder()
                .setPublicAccessPrevention(BucketInfo.PublicAccessPrevention.INHERITED)
                .build())
        .build()
        .update();

    System.out.println("Public access prevention is set to 'inherited' for " + bucketName);
  }
}

Node.js

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

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

以下範例會在值區上強制禁止公開存取:

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

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

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

// Enforces public access prevention for the bucket
async function setPublicAccessPreventionEnforced() {
  await storage.bucket(bucketName).setMetadata({
    iamConfiguration: {
      publicAccessPrevention: 'enforced',
    },
  });

  console.log(
    `Public access prevention is set to enforced for ${bucketName}.`
  );
}

setPublicAccessPreventionEnforced();

下例示範如何將值區的公開存取限制設為 inherited

/**
 * TODO(developer): Uncomment the following lines before running the sample.
 */
// The name of your GCS bucket
// const bucketName = 'Name of a bucket, e.g. my-bucket';
// Imports the Google Cloud client library
const {Storage} = require('@google-cloud/storage');

// Creates a client
const storage = new Storage();
async function setPublicAccessPreventionInherited() {
  // Sets public access prevention to 'inherited' for the bucket
  await storage.bucket(bucketName).setMetadata({
    iamConfiguration: {
      publicAccessPrevention: 'inherited',
    },
  });

  console.log(`Public access prevention is 'inherited' for ${bucketName}.`);
}

setPublicAccessPreventionInherited();

PHP

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

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

以下範例會在值區中強制禁止公開存取:

use Google\Cloud\Storage\StorageClient;

/**
 * Set the bucket Public Access Prevention to enforced.
 *
 * @param string $bucketName the name of your Cloud Storage bucket.
 *        (e.g. 'my-bucket')
 */
function set_public_access_prevention_enforced(string $bucketName): void
{
    $storage = new StorageClient();
    $bucket = $storage->bucket($bucketName);

    $bucket->update([
        'iamConfiguration' => [
            'publicAccessPrevention' => 'enforced'
        ]
    ]);

    printf(
        'Public Access Prevention has been set to enforced for %s.' . PHP_EOL,
        $bucketName
    );
}

下例示範如何將值區的公開存取限制設為 inherited

use Google\Cloud\Storage\StorageClient;

/**
 * Set the bucket Public Access Prevention to inherited.
 *
 * @param string $bucketName the name of your Cloud Storage bucket.
 *        (e.g. 'my-bucket')
 */
function set_public_access_prevention_inherited(string $bucketName): void
{
    $storage = new StorageClient();
    $bucket = $storage->bucket($bucketName);

    $bucket->update([
        'iamConfiguration' => [
            'publicAccessPrevention' => 'inherited'
        ]
    ]);

    printf(
        'Public Access Prevention has been set to inherited for %s.' . PHP_EOL,
        $bucketName
    );
}

Python

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

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

以下範例會在值區中強制禁止公開存取:

from google.cloud import storage
from google.cloud.storage.constants import PUBLIC_ACCESS_PREVENTION_ENFORCED


def set_public_access_prevention_enforced(bucket_name):
    """Enforce public access prevention for a bucket."""
    # The ID of your GCS bucket
    # bucket_name = "my-bucket"

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

    bucket.iam_configuration.public_access_prevention = (
        PUBLIC_ACCESS_PREVENTION_ENFORCED
    )
    bucket.patch()

    print(f"Public access prevention is set to enforced for {bucket.name}.")

下例示範如何將值區的公開存取限制設為 inherited


from google.cloud import storage
from google.cloud.storage.constants import PUBLIC_ACCESS_PREVENTION_INHERITED


def set_public_access_prevention_inherited(bucket_name):
    """Sets the public access prevention status to inherited, so that the bucket inherits its setting from its parent project."""
    # The ID of your GCS bucket
    # bucket_name = "my-bucket"

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

    bucket.iam_configuration.public_access_prevention = (
        PUBLIC_ACCESS_PREVENTION_INHERITED
    )
    bucket.patch()

    print(f"Public access prevention is 'inherited' for {bucket.name}.")

Ruby

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

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

以下範例會在值區中強制禁止公開存取:

def set_public_access_prevention_enforced 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.public_access_prevention = :enforced

  puts "Public access prevention is set to enforced for #{bucket_name}."
end

下例示範如何將值區的公開存取限制設為 inherited

def set_public_access_prevention_inherited 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.public_access_prevention = :inherited

  puts "Public access prevention is 'inherited' for #{bucket_name}."
end

REST API

JSON API

  1. 安裝並初始化 gcloud CLI,這樣您就能為 Authorization 標頭產生存取權杖。

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

     {
        "iamConfiguration": {
          "publicAccessPrevention": "STATE",
        }
      }
    

    其中 <var>STATE</var>enforcedinherited

  3. 使用 cURL 來透過包含所需 fieldsPATCH 值區要求呼叫 JSON API:

    curl -X PATCH --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?fields=iamConfiguration"

    其中:

    • JSON_FILE_NAME 是您在先前步驟中建立的 JSON 檔案路徑。
    • BUCKET_NAME 是相關值區的名稱。例如:my-bucket

XML API

XML API 無法用於管理不可公開存取限制。請改用 Google Cloud 控制台等其他 Cloud Storage 工具。

查看禁止公開存取狀態

如要查看個別值區的禁止公開存取狀態,請按照下列步驟操作:

控制台

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

    前往「Buckets」(值區) 頁面

  2. 按一下要查看其禁止公開存取狀態的 bucket 名稱。

  3. 按一下「Permissions」(權限) 分頁標籤。

  4. 「公開存取」資訊卡會顯示值區的狀態。

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

指令列

使用加上 --format 旗標的 gcloud storage buckets describe 指令:

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

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

如果成功,回應會類似以下範例:

public_access_prevention:inherited

用戶端程式庫

C++

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

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

namespace gcs = ::google::cloud::storage;
using ::google::cloud::StatusOr;
[](gcs::Client client, std::string const& bucket_name) {
  StatusOr<gcs::BucketMetadata> bucket_metadata =
      client.GetBucketMetadata(bucket_name);
  if (!bucket_metadata) throw std::move(bucket_metadata).status();

  if (bucket_metadata->has_iam_configuration() &&
      bucket_metadata->iam_configuration()
          .public_access_prevention.has_value()) {
    std::cout
        << "Public Access Prevention is "
        << *bucket_metadata->iam_configuration().public_access_prevention
        << " for bucket " << bucket_metadata->name() << "\n";
  } else {
    std::cout << "Public Access Prevention is not set for "
              << bucket_metadata->name() << "\n";
  }
}

C#

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

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


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

public class GetPublicAccessPreventionSample
{
    public string GetPublicAccessPrevention(string bucketName = "your-unique-bucket-name")
    {
        // Gets Bucket Metadata and prints publicAccessPrevention value (either "unspecified" or "enforced").
        var storage = StorageClient.Create();
        var bucket = storage.GetBucket(bucketName);
        var publicAccessPrevention = bucket.IamConfiguration.PublicAccessPrevention;

        Console.WriteLine($"Public access prevention is {publicAccessPrevention} for {bucketName}.");
        return publicAccessPrevention;
    }
}

Go

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

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

import (
	"context"
	"fmt"
	"io"
	"time"

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

// getPublicAccessPrevention gets the current public access prevention setting
// for the bucket, either "enforced" or "inherited".
func getPublicAccessPrevention(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()

	ctx, cancel := context.WithTimeout(ctx, time.Second*10)
	defer cancel()

	attrs, err := client.Bucket(bucketName).Attrs(ctx)
	if err != nil {
		return fmt.Errorf("Bucket(%q).Attrs: %w", bucketName, err)
	}
	fmt.Fprintf(w, "Public access prevention is %s for %v", attrs.PublicAccessPrevention, bucketName)
	return nil
}

Java

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

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

import com.google.cloud.storage.Bucket;
import com.google.cloud.storage.BucketInfo;
import com.google.cloud.storage.Storage;
import com.google.cloud.storage.StorageOptions;

public class GetPublicAccessPrevention {
  public static void getPublicAccessPrevention(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();
    Bucket bucket = storage.get(bucketName);

    // Gets Bucket Metadata and prints publicAccessPrevention value (either 'inherited' or
    // 'enforced').
    BucketInfo.PublicAccessPrevention publicAccessPrevention =
        bucket.getIamConfiguration().getPublicAccessPrevention();

    System.out.println(
        "Public access prevention is set to "
            + publicAccessPrevention.getValue()
            + " for "
            + bucketName);
  }
}

Node.js

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

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

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

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

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

async function getPublicAccessPrevention() {
  // Gets Bucket Metadata and prints publicAccessPrevention value (either 'inherited' or 'enforced').
  const [metadata] = await storage.bucket(bucketName).getMetadata();
  console.log(
    `Public access prevention is ${metadata.iamConfiguration.publicAccessPrevention} for ${bucketName}.`
  );
}

getPublicAccessPrevention();

PHP

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

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

use Google\Cloud\Storage\StorageClient;

/**
 * Get the Public Access Prevention setting for a bucket
 *
 * @param string $bucketName the name of your Cloud Storage bucket.
 *        (e.g. 'my-bucket')
 */
function get_public_access_prevention(string $bucketName): void
{
    $storage = new StorageClient();
    $bucket = $storage->bucket($bucketName);

    $iamConfiguration = $bucket->info()['iamConfiguration'];

    printf(
        'The bucket public access prevention is %s for %s.' . PHP_EOL,
        $iamConfiguration['publicAccessPrevention'],
        $bucketName
    );
}

Python

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

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

from google.cloud import storage


def get_public_access_prevention(bucket_name):
    """Gets the public access prevention setting (either 'inherited' or 'enforced') for a bucket."""
    # The ID of your GCS bucket
    # bucket_name = "my-bucket"

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

    print(
        f"Public access prevention is {iam_configuration.public_access_prevention} for {bucket.name}."
    )

Ruby

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

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

def get_public_access_prevention 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

  puts "Public access prevention is '#{bucket.public_access_prevention}' for #{bucket_name}."
end

REST API

JSON API

  1. 安裝並初始化 gcloud CLI,這樣您就能為 Authorization 標頭產生存取權杖。

  2. 使用 cURL 來透過包含所需 fieldsGET 值區要求呼叫 JSON API:

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

    其中 BUCKET_NAME 是相關值區的名稱。例如:my-bucket

    回應類似下列範例:

     {
      "iamConfiguration": {
          ...
          "publicAccessPrevention": "FLAG"
        }
      }

    其中 FLAGinheritedenforced

XML API

XML API 無法用於管理不可公開存取限制。請改用 Google Cloud 控制台等其他 Cloud Storage 工具。

使用機構政策

本節說明如何強制執行及移除禁止公開存取的機構政策,以及如何查看政策狀態。

設定禁止公開存取

如要在專案、資料夾或機構層級設定禁止公開存取功能,請按照下列步驟操作:

控制台

請按照「建立及管理機構政策」一文的操作說明,使用 storage.publicAccessPrevention 限制。

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

指令列

使用 gcloud beta resource-manager org-policies 指令:

gcloud beta resource-manager org-policies STATE \
  constraints/storage.publicAccessPrevention \
  --RESOURCE RESOURCE_ID

其中:

  • STATE 的值可能如下:

    • enable-enforce:強制禁止資源的公開存取。
    • disable-enforce:停用資源的「不可公開存取」限制。
    • delete:從資源中移除機構政策限制,讓資源繼承父項資源的值。
  • RESOURCE 是您要設定「不可公開存取」的資源。例如 organizationprojectfolder

  • RESOURCE_ID 是資源 ID。例如,123456789012 代表機構 ID245321 代表資料夾 ID,或是 my-pet-project 代表專案 ID

如需更多操作說明,請參閱「使用限制」。

以下是使用 disable-enforce 時的輸出範例:

etag: BwVJi0OOESU=
booleanPolicy: {}
constraint: constraints/storage.publicAccessPrevention

查看禁止公開存取狀態

如要查看專案、資料夾或機構層級的公開存取預防狀態,請按照下列步驟操作:

控制台

請按照「建立及管理機構政策」一文的操作說明,使用 storage.publicAccessPrevention 限制。

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

指令列

使用 describe --effective 指令:

gcloud beta resource-manager org-policies describe \
  constraints/storage.publicAccessPrevention --effective \
  --RESOURCE RESOURCE_ID

其中:

  • RESOURCE 是您要查看公開存取狀態的資源。例如 organizationprojectfolder

  • RESOURCE_ID 是資源 ID。例如,123456789012 代表機構 ID245321 代表資料夾 ID,而 my-pet-project 代表專案 ID

如需更多操作說明,請參閱「使用限制」。

後續步驟