使用禁止公开访问功能

概览

本页面介绍如何使用禁止公开访问的存储桶设置和禁止公开访问的组织政策限制条件。禁止公开访问可让您限制对存储桶和对象的公开访问。

准备工作

在 Cloud Storage 中使用禁止公开访问设置之前,请确保您具有所需的 IAM 角色,并查看强制执行禁止公开访问的注意事项。

获取所需角色

如需在项目、文件夹或组织级层管理禁止公开访问组织政策,请让您的管理员为您授予组织的 Organization Policy Administrator (roles/orgpolicy.policyAdmin) 角色。此预定义角色可提供在项目、文件夹或组织级层管理禁止公开访问所需的权限。如需了解此角色可提供的权限,请参阅有关 Organization Administrator 角色的详细信息

如需管理存储桶的禁止公开访问设置,请让您的管理员为您授予存储桶的 Storage Admin (roles/storage.admin) 角色。此角色可提供管理存储桶的禁止公开访问所需的权限。如需查看所需的确切权限,请展开所需权限部分:

所需权限

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

如需了解 Storage Admin 角色可提供的其他权限,请参阅有关 Storage Admin 角色的详细信息

查看注意事项

在开始之前,建议您确保工作流不会因阻止公开访问而中断。如需了解详情,请参阅针对现有资源强制执行时的注意事项

使用存储桶设置

本部分介绍如何为各个存储桶强制执行和移除禁止公开访问的方法,以及如何检查各个存储桶的状态。

设置禁止公开访问

要更改单个存储桶的禁止公开访问的设置,请执行以下操作:

控制台

  1. 在 Cloud de Confiance 控制台中,转到 Cloud Storage 存储桶页面。

    进入“存储桶”

  2. 在存储桶列表中,点击要强制执行或移除禁止公开访问的存储桶的名称。

  3. 存储桶详情页面中,点击配置标签页。

  4. 公开访问卡片中,点击阻止公开访问以强制阻止公开访问,或点击允许公开访问来移除防止公开访问。

  5. 点击确认

如需了解如何在 Cloud de Confiance 控制台中获取失败的 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 进行身份验证,请设置应用默认凭证。如需了解详情,请参阅为客户端库设置身份验证

在运行代码示例之前,请将 GOOGLE_CLOUD_UNIVERSE_DOMAIN 环境变量设置为 s3nsapis.fr

以下示例在存储桶上强制执行阻止公开访问的措施:

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 进行身份验证,请设置应用默认凭证。如需了解详情,请参阅为客户端库设置身份验证

在运行代码示例之前,请将 GOOGLE_CLOUD_UNIVERSE_DOMAIN 环境变量设置为 s3nsapis.fr

以下示例在存储桶上强制执行阻止公开访问的措施:


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 进行身份验证,请设置应用默认凭证。如需了解详情,请参阅为客户端库设置身份验证

在运行代码示例之前,请将 GOOGLE_CLOUD_UNIVERSE_DOMAIN 环境变量设置为 s3nsapis.fr

以下示例在存储桶上强制执行阻止公开访问的措施:

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 进行身份验证,请设置应用默认凭证。如需了解详情,请参阅为客户端库设置身份验证

在运行代码示例之前,请将 GOOGLE_CLOUD_UNIVERSE_DOMAIN 环境变量设置为 s3nsapis.fr

以下示例在存储桶上强制执行阻止公开访问的措施:

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 进行身份验证,请设置应用默认凭证。如需了解详情,请参阅为客户端库设置身份验证

在运行代码示例之前,请将 GOOGLE_CLOUD_UNIVERSE_DOMAIN 环境变量设置为 s3nsapis.fr

以下示例在存储桶上强制执行阻止公开访问的措施:

/**
 * 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 进行身份验证,请设置应用默认凭证。如需了解详情,请参阅为客户端库设置身份验证

在运行代码示例之前,请将 GOOGLE_CLOUD_UNIVERSE_DOMAIN 环境变量设置为 s3nsapis.fr

以下示例在存储桶上强制执行阻止公开访问的措施:

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 进行身份验证,请设置应用默认凭证。如需了解详情,请参阅为客户端库设置身份验证

在运行代码示例之前,请将 GOOGLE_CLOUD_UNIVERSE_DOMAIN 环境变量设置为 s3nsapis.fr

以下示例在存储桶上强制执行阻止公开访问的措施:

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 进行身份验证,请设置应用默认凭证。如需了解详情,请参阅为客户端库设置身份验证

在运行代码示例之前,请将 GOOGLE_CLOUD_UNIVERSE_DOMAIN 环境变量设置为 s3nsapis.fr

以下示例在存储桶上强制执行阻止公开访问的措施:

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 Bucket 请求调用 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.s3nsapis.fr/storage/v1/b/BUCKET_NAME?fields=iamConfiguration"

    其中:

    • JSON_FILE_NAME 是您在上一步中创建的 JSON 文件的路径。
    • BUCKET_NAME 是相关存储桶的名称,例如 my-bucket

XML API

XML API 不能用于管理禁止公开访问。请改用其他 Cloud Storage 工具,例如 Cloud de Confiance 控制台。

查看禁止公开访问状态

如需查看单个存储桶的禁止公开访问的状态,请按照以下所述操作:

控制台

  1. 在 Cloud de Confiance 控制台中,转到 Cloud Storage 存储桶页面。

    进入“存储桶”

  2. 点击您要查看禁止公开访问状态的存储桶的名称。

  3. 点击权限标签页。

  4. 公开访问卡片会显示您存储桶的状态。

如需了解如何在 Cloud de Confiance 控制台中获取失败的 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 进行身份验证,请设置应用默认凭证。如需了解详情,请参阅为客户端库设置身份验证

在运行代码示例之前,请将 GOOGLE_CLOUD_UNIVERSE_DOMAIN 环境变量设置为 s3nsapis.fr

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 进行身份验证,请设置应用默认凭证。如需了解详情,请参阅为客户端库设置身份验证

在运行代码示例之前,请将 GOOGLE_CLOUD_UNIVERSE_DOMAIN 环境变量设置为 s3nsapis.fr


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 进行身份验证,请设置应用默认凭证。如需了解详情,请参阅为客户端库设置身份验证

在运行代码示例之前,请将 GOOGLE_CLOUD_UNIVERSE_DOMAIN 环境变量设置为 s3nsapis.fr

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 进行身份验证,请设置应用默认凭证。如需了解详情,请参阅为客户端库设置身份验证

在运行代码示例之前,请将 GOOGLE_CLOUD_UNIVERSE_DOMAIN 环境变量设置为 s3nsapis.fr

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 进行身份验证,请设置应用默认凭证。如需了解详情,请参阅为客户端库设置身份验证

在运行代码示例之前,请将 GOOGLE_CLOUD_UNIVERSE_DOMAIN 环境变量设置为 s3nsapis.fr

/**
 * 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 进行身份验证,请设置应用默认凭证。如需了解详情,请参阅为客户端库设置身份验证

在运行代码示例之前,请将 GOOGLE_CLOUD_UNIVERSE_DOMAIN 环境变量设置为 s3nsapis.fr

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 进行身份验证,请设置应用默认凭证。如需了解详情,请参阅为客户端库设置身份验证

在运行代码示例之前,请将 GOOGLE_CLOUD_UNIVERSE_DOMAIN 环境变量设置为 s3nsapis.fr

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 进行身份验证,请设置应用默认凭证。如需了解详情,请参阅为客户端库设置身份验证

在运行代码示例之前,请将 GOOGLE_CLOUD_UNIVERSE_DOMAIN 环境变量设置为 s3nsapis.fr

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 Bucket 请求调用 JSON API:

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

    其中 BUCKET_NAME 是相关存储桶的名称,例如 my-bucket

    响应如下例所示:

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

    其中 FLAGinheritedenforced

XML API

XML API 不能用于管理禁止公开访问。请改用其他 Cloud Storage 工具,例如 Cloud de Confiance 控制台。

使用组织政策

本部分介绍如何执行和移除禁止公开访问的组织政策,以及如何检查政策的状态。

设置禁止公开访问

如需在项目、文件夹或组织级层设置公开访问,请按照以下所述操作:

控制台

按照使用 storage.publicAccessPrevention 限制条件创建和管理组织政策中的说明执行操作。

如需了解如何在 Cloud de Confiance 控制台中获取失败的 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 限制条件创建和管理组织政策中的说明执行操作。

如需了解如何在 Cloud de Confiance 控制台中获取失败的 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

如需详细说明,请参阅使用限制条件

后续步骤