Using Bucket Policy Only

This page shows you how to enable, disable and check the status of the Bucket Policy Only feature on a bucket in Cloud Storage. For details about this feature, see Bucket Policy Only.

Prerequisites

Before using this feature in Cloud Storage, you should:

  1. Have sufficient permission to view and update buckets in Cloud Storage:

    • If you own the project that contains the bucket, you most likely have the necessary permissions.

    • You should have the storage.buckets.update and storage.buckets.get IAM permissions on the relevant bucket. See Using IAM Permissions for instructions on how to get a role, such as roles/storage.admin, that has these permissions.

Enable Bucket Policy Only

To enable Bucket Policy Only on your bucket:

Console

  1. Open the Cloud Storage browser in the Google Cloud Platform Console.
    Open the Cloud Storage browser
  2. In the list of buckets, click on the name of the desired bucket.

  3. Select the Permissions tab near the top of the page.

  4. In the Simplify access control with Bucket Policy Only text box, click Enable.

  5. In the confirmation dialog that appears, click Confirm.

gsutil

Use the on option in a bucketpolicyonly set command, replacing [VALUES_IN_BRACKETS] with the appropriate values:

gsutil bucketpolicyonly set on gs://[BUCKET_NAME]/

If successful, the response looks like:

Enabling Bucket Policy Only for gs://test-bucket/...

Code samples

C++

For more information, see the Cloud Storage C++ API reference documentation .

namespace gcs = google::cloud::storage;
using google::cloud::StatusOr;
[](gcs::Client client, std::string bucket_name) {
  gcs::BucketIamConfiguration configuration;
  configuration.bucket_policy_only = gcs::BucketPolicyOnly{true};
  StatusOr<gcs::BucketMetadata> updated_metadata = client.PatchBucket(
      bucket_name, gcs::BucketMetadataPatchBuilder().SetIamConfiguration(
                       std::move(configuration)));

  if (!updated_metadata) {
    throw std::runtime_error(updated_metadata.status().message());
  }

  std::cout << "Successfully enabled Bucket Policy Only on bucket "
            << updated_metadata->name() << "\n";
}

C#

For more information, see the Cloud Storage C# API reference documentation .

        private void EnableBucketPolicyOnly(string bucketName)
        {
            var storage = StorageClient.Create();
            var bucket = storage.GetBucket(bucketName);
            bucket.IamConfiguration.BucketPolicyOnly.Enabled = true;
            bucket = storage.UpdateBucket(bucket, new UpdateBucketOptions()
            {
                // Use IfMetagenerationMatch to avoid race conditions.
                IfMetagenerationMatch = bucket.Metageneration,
            });

            Console.WriteLine($"Bucket Policy Only was enabled for {bucketName}.");
        }

Go

For more information, see the Cloud Storage Go API reference documentation .

bucket := c.Bucket(bucketName)
enableBucketPolicyOnly := storage.BucketAttrsToUpdate{
	BucketPolicyOnly: &storage.BucketPolicyOnly{
		Enabled: true,
	},
}
if _, err := bucket.Update(ctx, enableBucketPolicyOnly); err != nil {
	return err
}

Java

For more information, see the Cloud Storage Java API reference documentation .

// Instantiate a Google Cloud Storage client
Storage storage = StorageOptions.getDefaultInstance().getService();

// The name of a bucket, e.g. "my-bucket"
// String bucketName = "my-bucket";

BucketInfo.IamConfiguration iamConfiguration =
    BucketInfo.IamConfiguration.newBuilder().setIsBucketPolicyOnlyEnabled(true).build();
Bucket bucket =
    storage.update(
        BucketInfo.newBuilder(bucketName).setIamConfiguration(iamConfiguration).build());

System.out.println("Bucket Policy Only was enabled for " + bucketName);

Node.js

For more information, see the Cloud Storage Node.js API reference documentation .

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

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

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

// Enables Bucket Policy Only for the bucket
await storage.bucket(bucketName).setMetadata({
  iamConfiguration: {
    bucketPolicyOnly: {
      enabled: true,
    },
  },
});

console.log(`Bucket Policy Only was enabled for ${bucketName}.`);

PHP

For more information, see the Cloud Storage PHP API reference documentation .

use Google\Cloud\Storage\StorageClient;

/**
 * Enable Bucket Policy Only.
 *
 * @param string $bucketName Name of your Google Cloud Storage bucket.
 *
 * @return void
 */
function enable_bucket_policy_only($bucketName)
{
    $storage = new StorageClient();
    $bucket = $storage->bucket($bucketName);
    $bucket->update([
        'iamConfiguration' => [
            'bucketPolicyOnly' => [
              'enabled' => true
            ]
        ]
    ]);
    printf('Bucket Policy Only was enabled for %s' . PHP_EOL, $bucketName);
}

Python

For more information, see the Cloud Storage Python API reference documentation .

# bucket_name = "my-bucket"

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

bucket.iam_configuration.bucket_policy_only_enabled = True
bucket.patch()

print('Bucket Policy Only was enabled for {}.'.format(bucket.name))

Ruby

For more information, see the Cloud Storage Ruby API reference documentation .

# project_id  = "Your Google Cloud project ID"
# bucket_name = "Name of your Google Cloud Storage bucket"

require "google/cloud/storage"

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

bucket.policy_only = true

puts "Bucket Policy Only was enabled for #{bucket_name}."

REST APIs

JSON API

  1. Get an authorization access token from the OAuth 2.0 Playground. Configure the playground to use your own OAuth credentials.
  2. Create a .json file that contains the following information, replacing [VALUES_IN_BRACKETS] with the appropriate values:

    {
      "iamConfiguration": {
          "bucketPolicyOnly": {
            "enabled": true
          }
      }
    }
  3. Use cURL to call the JSON API with a PATCH Bucket request, replacing [VALUES_IN_BRACKETS] with the appropriate values:

    curl -X PATCH --data-binary @[JSON_FILE_NAME].json \
    -H "Authorization: Bearer [OAUTH2_TOKEN]" \
    -H "Content-Type: application/json" \
    "https://www.googleapis.com/storage/v1/b/[BUCKET_NAME]?fields=iamConfiguration"

XML API

The XML API cannot be used to work with Bucket Policy Only. Use one of the other Cloud Storage tools, such as gsutil, instead.

View Bucket Policy Only status

Console

  1. Open the Cloud Storage browser in the Google Cloud Platform Console.
    Open the Cloud Storage browser
  2. In the Columns drop-down menu, make sure Access control model is checked.

  3. In the list of buckets, the Bucket Policy Only status of each bucket is found in the Access control model column.

gsutil

Use the bucketpolicyonly get command, replacing [VALUES_IN_BRACKETS] with the appropriate values:

gsutil bucketpolicyonly get gs://[BUCKET_NAME]/

If Bucket Policy Only is enabled, the response looks like:

Bucket Policy Only setting for gs://[BUCKET_NAME]/:
    Enabled: True
    LockedTime: [LOCK_DATE] 

Code samples

C++

For more information, see the Cloud Storage C++ API reference documentation .

namespace gcs = google::cloud::storage;
using google::cloud::StatusOr;
[](gcs::Client client, std::string bucket_name) {
  StatusOr<gcs::BucketMetadata> bucket_metadata =
      client.GetBucketMetadata(bucket_name);

  if (!bucket_metadata) {
    throw std::runtime_error(bucket_metadata.status().message());
  }

  if (bucket_metadata->has_iam_configuration() &&
      bucket_metadata->iam_configuration().bucket_policy_only.has_value()) {
    gcs::BucketPolicyOnly bucket_policy_only =
        *bucket_metadata->iam_configuration().bucket_policy_only;

    std::cout << "Bucket Policy Only is enabled for "
              << bucket_metadata->name() << "\n";
    std::cout << "Bucket will be locked on " << bucket_policy_only << "\n";
  } else {
    std::cout << "Bucket Policy Only is not enabled for "
              << bucket_metadata->name() << "\n";
  }
}

C#

For more information, see the Cloud Storage C# API reference documentation .

        private void GetBucketPolicyOnly(string bucketName)
        {
            var storage = StorageClient.Create();
            var bucket = storage.GetBucket(bucketName);
            var bucketPolicyOnly = bucket.IamConfiguration.BucketPolicyOnly;

            bool? enabledOrNull = bucketPolicyOnly?.Enabled;
            bool bucketPolicyEnabled =
                enabledOrNull.HasValue ? enabledOrNull.Value : false;
            if (bucketPolicyEnabled)
            {
                Console.WriteLine($"Bucket Policy Only is enabled for {bucketName}.");
                Console.WriteLine(
                    $"Bucket Policy Only will be locked on {bucketPolicyOnly.LockedTime}.");
            }
            else
            {
                Console.WriteLine($"Bucket Policy Only is not enabled for {bucketName}.");
            }
        }

Go

For more information, see the Cloud Storage Go API reference documentation .

attrs, err := c.Bucket(bucketName).Attrs(ctx)
if err != nil {
	return nil, err
}
bucketPolicyOnly := attrs.BucketPolicyOnly
if bucketPolicyOnly.Enabled {
	log.Printf("Bucket Policy Only is enabled for %q.\n",
		attrs.Name)
	log.Printf("Bucket will be locked on %q.\n",
		bucketPolicyOnly.LockedTime)
} else {
	log.Printf("Bucket Policy Only is not enabled for %q.\n",
		attrs.Name)
}

Java

For more information, see the Cloud Storage Java API reference documentation .

// Instantiate a Google Cloud Storage client
Storage storage = StorageOptions.getDefaultInstance().getService();

// The name of a bucket, e.g. "my-bucket"
// String bucketName = "my-bucket";

Bucket bucket = storage.get(bucketName, BucketGetOption.fields(BucketField.IAMCONFIGURATION));
BucketInfo.IamConfiguration iamConfiguration = bucket.getIamConfiguration();

Boolean enabled = iamConfiguration.isBucketPolicyOnlyEnabled();
Date lockedTime = new Date(iamConfiguration.getBucketPolicyOnlyLockedTime());

if (enabled != null && enabled) {
  System.out.println("Bucket Policy Only is enabled for " + bucketName);
  System.out.println("Bucket will be locked on " + lockedTime);
} else {
  System.out.println("Bucket Policy Only is disabled for " + bucketName);
}

Node.js

For more information, see the Cloud Storage Node.js API reference documentation .

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

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

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

// Gets Bucket Metadata and checks if BucketPolicyOnly is enabled.
const [metadata] = await storage.bucket(bucketName).getMetadata();

if (metadata.hasOwnProperty('iamConfiguration')) {
  const bucketPolicyOnly = metadata.iamConfiguration.bucketPolicyOnly;
  console.log(`Bucket Policy Only is enabled for ${bucketName}.`);
  console.log(`Bucket will be locked on ${bucketPolicyOnly.lockedTime}.`);
} else {
  console.log(`Bucket Policy Only is not enabled for ${bucketName}.`);
}

PHP

For more information, see the Cloud Storage PHP API reference documentation .

use Google\Cloud\Storage\StorageClient;

/**
 * Enable Bucket Policy Only.
 *
 * @param string $bucketName Name of your Google Cloud Storage bucket.
 *
 * @return void
 */
function get_bucket_policy_only($bucketName)
{
    $storage = new StorageClient();
    $bucket = $storage->bucket($bucketName);
    $bucketInformation = $bucket->info();
    $bucketPolicyOnly = $bucketInformation['iamConfiguration']['bucketPolicyOnly'];
    if ($bucketPolicyOnly['enabled']) {
        printf('Bucket Policy Only is enabled for %s' . PHP_EOL, $bucketName);
        printf('Bucket Policy Only will be locked on %s' . PHP_EOL, $bucketPolicyOnly['LockedTime']);
    } else {
        printf('Bucket Policy Only is disabled for %s' . PHP_EOL, $bucketName);
    }
}

Python

For more information, see the Cloud Storage Python API reference documentation .

# bucket_name = "my-bucket"

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

if iam_configuration.bucket_policy_only_enabled:
    print('Bucket Policy Only is enabled for {}.'.format(bucket.name))
    print('Bucket will be locked on {}.'.format(
        iam_configuration.bucket_policy_only_locked_time))
else:
    print('Bucket Policy Only is disabled for {}.'.format(bucket.name))

Ruby

For more information, see the Cloud Storage Ruby API reference documentation .

# project_id  = "Your Google Cloud project ID"
# bucket_name = "Name of your Google Cloud Storage bucket"

require "google/cloud/storage"

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

if bucket.policy_only?
  puts "Bucket Policy Only is enabled for #{bucket_name}."
  puts "Bucket will be locked on #{bucket.policy_only_locked_at}."
else
  puts "Bucket Policy Only is disabled for #{bucket_name}."
end

REST APIs

JSON API

  1. Get an authorization access token from the OAuth 2.0 Playground. Configure the playground to use your own OAuth credentials.
  2. Use cURL to call the JSON API with a GET Bucket request that includes the desired fields, replacing [VALUES_IN_BRACKETS] with the appropriate values:

    curl -X GET -H "Authorization: Bearer [OAUTH2_TOKEN]" \
    "https://www.googleapis.com/storage/v1/b/[BUCKET_NAME]?fields=iamConfiguration"

    If the bucket has Bucket Policy Only enabled, the response looks like the following example:

    {
      "iamConfiguration": {
          "bucketPolicyOnly": {
            "enabled": true,
            "lockedTime": "[LOCK_DATE]"
          }
        }
      }

XML API

The XML API cannot be used to work with Bucket Policy Only. Use one of the other Cloud Storage tools, such as gsutil, instead.

Disable Bucket Policy Only

To disable Bucket Policy Only on your bucket:

Console

  1. Open the Cloud Storage browser in the Google Cloud Platform Console.
    Open the Cloud Storage browser
  2. In the list of buckets, click on the name of the desired bucket.

  3. Select the Permissions tab near the top of the page.

  4. In the Object-level permissions are disabled text box, click Enable.

  5. In the confirmation dialog that appears, click Confirm.

gsutil

Use the off option in a bucketpolicyonly set command, replacing [VALUES_IN_BRACKETS] with the appropriate values:

gsutil bucketpolicyonly set off gs://[BUCKET_NAME]/

If successful, the response looks like:

Disabling Bucket Policy Only for gs://test-bucket/...

Code samples

C++

For more information, see the Cloud Storage C++ API reference documentation .

namespace gcs = google::cloud::storage;
using google::cloud::StatusOr;
[](gcs::Client client, std::string bucket_name) {
  gcs::BucketIamConfiguration configuration;
  configuration.bucket_policy_only = gcs::BucketPolicyOnly{false};
  StatusOr<gcs::BucketMetadata> updated_metadata = client.PatchBucket(
      bucket_name, gcs::BucketMetadataPatchBuilder().SetIamConfiguration(
                       std::move(configuration)));

  if (!updated_metadata) {
    throw std::runtime_error(updated_metadata.status().message());
  }

  std::cout << "Successfully disabled Bucket Policy Only on bucket "
            << updated_metadata->name() << "\n";
}

C#

For more information, see the Cloud Storage C# API reference documentation .

        private void DisableBucketPolicyOnly(string bucketName)
        {
            var storage = StorageClient.Create();
            var bucket = storage.GetBucket(bucketName);
            bucket.IamConfiguration.BucketPolicyOnly.Enabled = false;
            bucket = storage.UpdateBucket(bucket, new UpdateBucketOptions()
            {
                // Use IfMetagenerationMatch to avoid race conditions.
                IfMetagenerationMatch = bucket.Metageneration,
            });

            Console.WriteLine($"Bucket Policy Only was disabled for {bucketName}.");
        }

Go

For more information, see the Cloud Storage Go API reference documentation .

bucket := c.Bucket(bucketName)
disableBucketPolicyOnly := storage.BucketAttrsToUpdate{
	BucketPolicyOnly: &storage.BucketPolicyOnly{
		Enabled: false,
	},
}
if _, err := bucket.Update(ctx, disableBucketPolicyOnly); err != nil {
	return err
}

Java

For more information, see the Cloud Storage Java API reference documentation .

// Instantiate a Google Cloud Storage client
Storage storage = StorageOptions.getDefaultInstance().getService();

// The name of a bucket, e.g. "my-bucket"
// String bucketName = "my-bucket";

BucketInfo.IamConfiguration iamConfiguration =
    BucketInfo.IamConfiguration.newBuilder().setIsBucketPolicyOnlyEnabled(false).build();
Bucket bucket =
    storage.update(
        BucketInfo.newBuilder(bucketName).setIamConfiguration(iamConfiguration).build());

System.out.println("Bucket Policy Only was disabled for " + bucketName);

Node.js

For more information, see the Cloud Storage Node.js API reference documentation .

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

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

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

// Disables Bucket Policy Only for the bucket
await storage.bucket(bucketName).setMetadata({
  iamConfiguration: {
    bucketPolicyOnly: {
      enabled: false,
    },
  },
});

console.log(`Bucket Policy Only was disabled for ${bucketName}.`);

PHP

For more information, see the Cloud Storage PHP API reference documentation .

use Google\Cloud\Storage\StorageClient;

/**
 * Enable Bucket Policy Only.
 *
 * @param string $bucketName Name of your Google Cloud Storage bucket.
 *
 * @return void
 */
function disable_bucket_policy_only($bucketName)
{
    $storage = new StorageClient();
    $bucket = $storage->bucket($bucketName);
    $bucket->update([
        'iamConfiguration' => [
            'bucketPolicyOnly' => [
              'enabled' => false
            ]
        ]
    ]);
    printf('Bucket Policy Only was disabled for %s' . PHP_EOL, $bucketName);
}

Python

For more information, see the Cloud Storage Python API reference documentation .

# bucket_name = "my-bucket"

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

bucket.iam_configuration.bucket_policy_only_enabled = False
bucket.patch()

print('Bucket Policy Only was disabled for {}.'.format(bucket.name))

Ruby

For more information, see the Cloud Storage Ruby API reference documentation .

# project_id  = "Your Google Cloud project ID"
# bucket_name = "Name of your Google Cloud Storage bucket"

require "google/cloud/storage"

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

bucket.policy_only = false

puts "Bucket Policy Only was disabled for #{bucket_name}."

REST APIs

JSON API

  1. Get an authorization access token from the OAuth 2.0 Playground. Configure the playground to use your own OAuth credentials.
  2. Create a .json file that contains the following information, replacing [VALUES_IN_BRACKETS] with the appropriate values:

    {
      "iamConfiguration": {
          "bucketPolicyOnly": {
            "enabled": false
          }
      }
    }
  3. Use cURL to call the JSON API with a PATCH Bucket request, replacing [VALUES_IN_BRACKETS] with the appropriate values:

    curl -X PATCH --data-binary @[JSON_FILE_NAME].json \
    -H "Authorization: Bearer [OAUTH2_TOKEN]" \
    -H "Content-Type: application/json" \
    "https://www.googleapis.com/storage/v1/b/[BUCKET_NAME]?fields=iamConfiguration"

XML API

The XML API cannot be used to work with Bucket Policy Only. Use one of the other Cloud Storage tools, such as gsutil, instead.

What's next

Var denne side nyttig? Giv os en anmeldelse af den:

Send feedback om...

Har du brug for hjælp? Besøg vores supportside.