使用禁止公開存取功能

總覽

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

事前準備

在 Cloud Storage 中使用禁止公開存取功能前,請確認您具備必要的 IAM 角色,並詳閱強制執行禁止公開存取功能的注意事項。

取得必要角色

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

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

所需權限

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

如要瞭解「儲存空間管理員」角色包含的其他權限,請參閱儲存空間管理員角色詳細資料

審查注意事項

開始前,建議您先確認封鎖公開存取權後,不會導致任何工作流程中斷。詳情請參閱「對現有資源強制執行時的注意事項」。

使用 bucket 設定

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

設定禁止公開存取

如要變更個別 bucket 的公開存取預防設定,請按照下列指示操作:

控制台

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

    前往「Buckets」(值區) 頁面

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

  3. 前往「Bucket details」(值區詳細資料) 頁面,點選「Permissions」(權限) 分頁標籤。

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

  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 進行驗證,請設定應用程式預設憑證。詳情請參閱「設定用戶端程式庫的驗證作業」。

以下範例會強制禁止公開存取 bucket:

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";
}

下例示範如何為 bucket 將公開存取權禁止設定為 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 進行驗證,請設定應用程式預設憑證。詳情請參閱「設定用戶端程式庫的驗證作業」。

以下範例會強制禁止公開存取 bucket:


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;
    }
}

下例示範如何為 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 進行驗證,請設定應用程式預設憑證。詳情請參閱「設定用戶端程式庫的驗證作業」。

以下範例會強制禁止公開存取 bucket:

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
}

下例示範如何為 bucket 將公開存取權禁止設定為 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 進行驗證,請設定應用程式預設憑證。詳情請參閱「設定用戶端程式庫的驗證作業」。

以下範例會強制禁止公開存取 bucket:

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

下例示範如何為 bucket 將公開存取權禁止設定為 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 進行驗證,請設定應用程式預設憑證。詳情請參閱「設定用戶端程式庫的驗證作業」。

以下範例會強制禁止公開存取 bucket:

/**
 * 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();

下例示範如何為 bucket 將公開存取權禁止設定為 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 進行驗證,請設定應用程式預設憑證。詳情請參閱「設定用戶端程式庫的驗證作業」。

以下範例會強制禁止公開存取 bucket:

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

下例示範如何為 bucket 將公開存取權禁止設定為 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 進行驗證,請設定應用程式預設憑證。詳情請參閱「設定用戶端程式庫的驗證作業」。

以下範例會強制禁止公開存取 bucket:

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}.")

下例示範如何為 bucket 將公開存取權禁止設定為 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 進行驗證,請設定應用程式預設憑證。詳情請參閱「設定用戶端程式庫的驗證作業」。

以下範例會強制禁止公開存取 bucket:

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

下例示範如何為 bucket 將公開存取權禁止設定為 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 無法用來管理「不可公開存取」限制。請改用其他 Cloud Storage 工具,例如 Google Cloud 控制台。

查看禁止公開存取狀態

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

控制台

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

    前往「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 無法用來管理「不可公開存取」限制。請改用其他 Cloud Storage 工具,例如 Google Cloud 控制台。

使用機構政策

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

設定禁止公開存取

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

控制台

請按照「建立及管理機構政策」的指示,使用 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 代表資料夾 IDmy-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 代表資料夾 IDmy-pet-project 則代表專案 ID

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

後續步驟