Creating and Managing Access Control Lists (ACLs)

This page describes how to control access to buckets and objects using Access Control Lists (ACLs). ACLs are a mechanism you can use to define who has access to your buckets and objects, as well as what level of access they have. To learn more about ACLs, read the Overview of ACLs.

To learn about other ways to control access to buckets and objects, read Overview of Access Control.

Before you begin

Should you use ACLs?

In most cases, Identity and Access Management (IAM) is the recommended method for controlling access to your resources, because it provides enterprise-grade access control across all of Google Cloud Platform, and it allows permissions granted to parent resources, such as projects, to be inherited by child resources, such as buckets and objects. See Using IAM Permissions for guides to working with IAM in Cloud Storage.

You most likely want to use ACLs if you need to customize access to individual objects within a bucket, because IAM permissions apply to all objects within a bucket. However, you should still use IAM for any access that is common to all objects in a bucket, as this reduces the amount of fine-grained managing you have to do.

Do you need to set an ACL?

Depending on the permission that you want a bucket or object to have, you might not need to set an ACL. Buckets and objects are created with default ACLs that might already contain the permission that you want the bucket or object to have.

Use the following guidance to decide if you should set an ACL.

On buckets:

Console

New buckets are created with the predefined project-private ACL. If your bucket needs a different permission, set an ACL.

gsutil

New buckets are added as project-private. If your bucket needs a different permission, set an ACL.

JSON API

By default, new buckets are added as project-private. If your bucket needs a different permission, set an ACL.

XML API

New buckets are added as project-private. If your bucket needs a different permission, set an ACL.

As noted above, every bucket has a default object ACL that is applied to all objects uploaded to that bucket that do not have a predefined ACL or (if you are using the JSON API) an ACL specified in the request. Read more in Default object ACLs.

On objects:

Console

Uploaded objects get the same ACLs as the bucket object, and the uploader is added as owner to the ACL. If your object needs a different permission, set an ACL.

gsutil

New objects are added with the default object ACL for the bucket. When copying an object already stored in the cloud, you can override this behavior with the -p option.

JSON API

By default, new objects are added with the default object ACL for the bucket.

XML API

New objects are added with the default object ACL for the bucket.

Which interface should you use?

The examples below show how to configure access control using the Google Cloud Platform Console, the gsutil command line tool, the Cloud Storage Client Libraries, and the XML and JSON APIs. Use these guidelines to choose which one to use:

  • If you are new to access control and only wish to modify ACLs for individual objects, use the Cloud Platform Console.

  • If you are new to access control and wish to modify ACLs for buckets and objects, use gsutil.

  • If you have experience with one of the Cloud Storage Client Libraries, use it for managing your ACLs.

  • If you are specifying ACLs using an API, you should have previous experience making HTTP requests. You can use your favorite tool or application to send the HTTP requests. In the examples, we use the cURL tool. You can get authorization tokens to use in the cURL examples from the OAuth 2.0 Playground.

Setting ACLs

The tool or API you use to set and get ACLs determines the ACL syntax you use. The ACL syntaxes look different, but they contain the same ACL information: entries that grant permissions to scopes.

Console

  1. Go to the Cloud Storage browser in the Google Cloud Platform Console.
    Go to the Cloud Storage browser

  2. Navigate to the object whose ACL you want to modify.

  3. Choose Edit Permissions from the drop down menu for the object.

    You should see a permission dialog that looks like:

    This screenshot shows an ACL with four entries:

    • In the first entry, all owners of a specific project (one whose project number is 867489140601) receive "Owner" access/permission for this object.
    • In the second entry, all editors of a specific project (one whose project number is 867489140601) also receive "Owner" access/permission for this object.
    • In the third entry, all viewers of a specific project (one whose project number is 867489140601) receive "Reader" access/permission for this object.
    • In the fourth entry, the user who uploaded the object receives "Owner" access/permission for the object. Object uploaders are always set as an "Owner" and cannot be removed.
  4. Click Add item.

  5. Choose the type of Entity to give permission to.

    Entity specifies the type of thing that's getting the permission (for example a user or a group). Refer to Access Control Scopes for a list of supported values for Entity.

  6. Enter a value in Name.

    Name identifies a specific user, group, or other entity type. Refer to Access Control Scopes for a list of supported values for Name.

    Together, Entity and Name define who the permission applies to.

  7. Choose a value in Access.

    Access defines the permission that you want to set on the object. Refer to Access Control Permissions for a list of supported values for Access.

  8. Click Save.

gsutil

Use gsutil acl to specify ACLs:

  • To specify individual grants:

    gsutil acl ch -u [USER_EMAIL]:[PERMISSION] gs://[BUCKET_NAME]

  • To specify canned ACLs:

    gsutil acl set [CANNED_ACL_NAME] gs://[BUCKET_NAME]

  • To specify ACLs in JSON format:

    gsutil acl set [JSON_FILE] gs://[bucket-name]

    where [JSON_FILE] contains ACLs specified in JSON format.

Client libraries

C#

For more on installing and creating a Cloud Storage client, refer to Cloud Storage Client Libraries.

The following sample adds an ACL to a bucket:

private void AddBucketOwner(string bucketName, string userEmail)
{
    var storage = StorageClient.Create();
    var bucket = storage.GetBucket(bucketName, new GetBucketOptions()
    {
        Projection = Projection.Full
    });
    if (null == bucket.Acl)
    {
        bucket.Acl = new List<BucketAccessControl>();
    }
    bucket.Acl.Add(new BucketAccessControl()
    {
        Bucket = bucketName,
        Entity = $"user-{userEmail}",
        Role = "OWNER",
    });
    var updatedBucket = storage.UpdateBucket(bucket, new UpdateBucketOptions()
    {
        // Avoid race conditions.
        IfMetagenerationMatch = bucket.Metageneration,
    });
}

The following sample adds an ACL to an object:

private void AddObjectOwner(string bucketName, string objectName,
    string userEmail)
{
    var storage = StorageClient.Create();
    var storageObject = storage.GetObject(bucketName, objectName,
        new GetObjectOptions() { Projection = Projection.Full });
    if (null == storageObject.Acl)
    {
        storageObject.Acl = new List<ObjectAccessControl>();
    }
    storageObject.Acl.Add(new ObjectAccessControl()
    {
        Bucket = bucketName,
        Entity = $"user-{userEmail}",
        Role = "OWNER",
    });
    var updatedObject = storage.UpdateObject(storageObject, new UpdateObjectOptions()
    {
        // Avoid race conditions.
        IfMetagenerationMatch = storageObject.Metageneration,
    });
}

Go

For more on installing and creating a Cloud Storage client, refer to Cloud Storage Client Libraries.

The following sample adds an ACL to a bucket:

func addBucketACL(client *storage.Client, bucket string) error {
	ctx := context.Background()

	acl := client.Bucket(bucket).ACL()
	if err := acl.Set(ctx, storage.AllAuthenticatedUsers, storage.RoleReader); err != nil {
		return err
	}
	return nil
}

The following sample adds an ACL to an object:

func addObjectACL(client *storage.Client, bucket, object string) error {
	ctx := context.Background()

	acl := client.Bucket(bucket).Object(object).ACL()
	if err := acl.Set(ctx, storage.AllAuthenticatedUsers, storage.RoleReader); err != nil {
		return err
	}
	return nil
}

Java

For more on installing and creating a Cloud Storage client, refer to Cloud Storage Client Libraries.

The following sample adds an ACL to a bucket:

Acl acl = storage.createAcl(bucketName, Acl.of(User.ofAllAuthenticatedUsers(), Role.READER));

The following sample adds an ACL to an object:

BlobId blobId = BlobId.of(bucketName, blobName, blobGeneration);
Acl acl = storage.createAcl(blobId, Acl.of(User.ofAllAuthenticatedUsers(), Role.READER));

Node.js

For more on installing and creating a Cloud Storage client, refer to Cloud Storage Client Libraries.

The following sample adds an ACL to a bucket:

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

// The name of the bucket to access, e.g. "my-bucket"
// const bucketName = "my-bucket";

// The email of the user to add, e.g. "developer@company.com"
// const userEmail = "developer@company.com";

// Instantiates a client
const storage = Storage();

// Makes the user an owner of the bucket. You can use addAllUsers(),
// addDomain(), addProject(), addGroup(), and addAllAuthenticatedUsers()
// to grant access to different types of entities. You can also use "readers"
// and "writers" to grant different roles.
storage
  .bucket(bucketName)
  .acl
  .owners
  .addUser(userEmail)
  .then(() => {
    console.log(`Added user ${userEmail} as an owner on bucket ${bucketName}.`);
  })
  .catch((err) => {
    console.error('ERROR:', err);
  });

The following sample adds an ACL to an object:

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

// The name of the bucket to access, e.g. "my-bucket"
// const bucketName = "my-bucket";

// The name of the file to access, e.g. "file.txt"
// const filename = "file.txt";

// The email of the user to add, e.g. "developer@company.com"
// const userEmail = "developer@company.com";

// Instantiates a client
const storage = Storage();

// Makes the user an owner of the file. You can use addAllUsers(),
// addDomain(), addProject(), addGroup(), and addAllAuthenticatedUsers()
// to grant access to different types of entities. You can also use "readers"
// and "writers" to grant different roles.
storage
  .bucket(bucketName)
  .file(filename)
  .acl
  .owners
  .addUser(userEmail)
  .then(() => {
    console.log(`Added user ${userEmail} as an owner on file ${filename}.`);
  })
  .catch((err) => {
    console.error('ERROR:', err);
  });

PHP

For more on installing and creating a Cloud Storage client, refer to Cloud Storage Client Libraries.

The following sample adds an ACL to a bucket:

use Google\Cloud\Storage\StorageClient;

/**
 * Add an entity and role to a bucket's ACL.
 *
 * @param string $bucketName the name of your Cloud Storage bucket.
 * @param string $entity The entity to update access controls for.
 * @param string $role The permissions to add for the specified entity. May
 *        be one of 'OWNER', 'READER', or 'WRITER'.
 * @param array $options
 *
 * @return void
 */
function add_bucket_acl($bucketName, $entity, $role, $options = [])
{
    $storage = new StorageClient();
    $bucket = $storage->bucket($bucketName);
    $acl = $bucket->acl();
    $acl->add($entity, $role, $options);
    printf('Added %s (%s) to gs://%s ACL' . PHP_EOL, $entity, $role, $bucketName);
}

The following sample adds an ACL to an object:

use Google\Cloud\Storage\StorageClient;

/**
 * Add an entity and role to an object's ACL.
 *
 * @param string $bucketName the name of your Cloud Storage bucket.
 * @param string $objectName the name of your Cloud Storage object.
 * @param string $entity The entity to update access controls for.
 * @param string $role The permissions to add for the specified entity. May
 *        be one of 'OWNER', 'READER', or 'WRITER'.
 * @param array $options
 *
 * @return void
 */
function add_object_acl($bucketName, $objectName, $entity, $role, $options = [])
{
    $storage = new StorageClient();
    $bucket = $storage->bucket($bucketName);
    $object = $bucket->object($objectName);
    $acl = $object->acl();
    $acl->add($entity, $role, $options);
    printf('Added %s (%s) to gs://%s/%s ACL' . PHP_EOL, $entity, $role, $bucketName, $objectName);
}

Python

For more on installing and creating a Cloud Storage client, refer to Cloud Storage Client Libraries.

The following sample adds an ACL to a bucket:

def add_bucket_owner(bucket_name, user_email):
    """Adds a user as an owner on the given bucket."""
    storage_client = storage.Client()
    bucket = storage_client.bucket(bucket_name)

    # Reload fetches the current ACL from Cloud Storage.
    bucket.acl.reload()

    # You can also use `group()`, `domain()`, `all_authenticated()` and `all()`
    # to grant access to different types of entities.
    # You can also use `grant_read()` or `grant_write()` to grant different
    # roles.
    bucket.acl.user(user_email).grant_owner()
    bucket.acl.save()

    print('Added user {} as an owner on bucket {}.'.format(
        user_email, bucket_name))

The following sample adds an ACL to an object:

def add_blob_owner(bucket_name, blob_name, user_email):
    """Adds a user as an owner on the given blob."""
    storage_client = storage.Client()
    bucket = storage_client.bucket(bucket_name)
    blob = bucket.blob(blob_name)

    # Reload fetches the current ACL from Cloud Storage.
    blob.acl.reload()

    # You can also use `group`, `domain`, `all_authenticated` and `all` to
    # grant access to different types of entities. You can also use
    # `grant_read` or `grant_write` to grant different roles.
    blob.acl.user(user_email).grant_owner()
    blob.acl.save()

    print('Added user {} as an owner on blob {} in bucket {}.'.format(
        user_email, blob_name, bucket_name))

Ruby

For more on installing and creating a Cloud Storage client, refer to Cloud Storage Client Libraries.

The following sample adds an ACL to a bucket:

# project_id  = "Your Google Cloud project ID"
# bucket_name = "Your Google Cloud Storage bucket name"
# email       = "Google Cloud Storage ACL Entity email"

require "google/cloud/storage"

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

bucket.acl.add_owner email

puts "Added OWNER permission for #{email} to #{bucket_name}"

The following sample adds an ACL to an object:

# project_id  = "Your Google Cloud project ID"
# bucket_name = "Your Google Cloud Storage bucket name"
# file_name   = "Name of a file in the Storage bucket"
# email       = "Google Cloud Storage ACL Entity email"

require "google/cloud/storage"

storage = Google::Cloud::Storage.new project: project_id
bucket  = storage.bucket bucket_name
file    = bucket.file file_name

file.acl.add_owner email

puts "Added OWNER permission for #{email} to #{file_name}"

JSON API

When creating a bucket, you can specify the acl[] property in an insert request. For an existing bucket, specify the acl[] property in a patch or update request.

When creating an object, you can specify the acl[] property in the request body or the predefinedAcl query parameter in an insert request. For an existing object, specify the acl[] property or the predefinedAcl query parameter in a patch or update request.

For definitions of the bucket and object ACL properties, see the BucketAccessControls and ObjectAccessControls resources, respectively.

The following example shows different bucket ACL entries.

"acl": [
  {
   "kind": "storage#bucketAccessControl",
   "id": "example-bucket/project-owners-123412341234",
   "selfLink": "https://www.googleapis.com/storage/v1/b/example-bucket/acl/project-owners-123412341234",
   "bucket": "example-bucket",
   "entity": "project-owners-123412341234",
   "role": "OWNER",
   "projectTeam": {
       "projectNumber": "123412341234",
       "team": "owners"
   },
   "etag": "CDk="
  },
  {
   "kind": "storage#bucketAccessControl",
   "id": "example-bucket/project-editors-123412341234",
   "selfLink": "https://www.googleapis.com/storage/v1/b/example-bucket/acl/project-editors-123412341234",
   "bucket": "example-bucket",
   "entity": "project-editors-123412341234",
   "role": "OWNER",
   "projectTeam": {
     "projectNumber": "123412341234",
     "team": "editors"
   },
   "etag": "CDk="
  },
  {
   "kind": "storage#bucketAccessControl",
   "id": "example-bucket/project-viewers-123412341234",
   "selfLink": "https://www.googleapis.com/storage/v1/b/example-bucket/acl/project-viewers-123412341234",
   "bucket": "example-bucket",
   "entity": "project-viewers-123412341234",
   "role": "READER",
   "projectTeam": {
     "projectNumber": "123412341234",
     "team": "viewers"
   },
   "etag": "CDk="
  },
  {
   "kind": "storage#bucketAccessControl",
   "id": "example-bucket/group-gs-announce@googlegroups.com",
   "selfLink": "https://www.googleapis.com/storage/v1/b/example-bucket/acl/group-gs-announce@googlegroups.com",
   "bucket": "example-bucket",
   "entity": "group-gs-announce@googlegroups.com",
   "role": "READER",
   "email": "gs-announce@googlegroups.com",
   "etag": "CDk="
  },
  {
   "kind": "storage#bucketAccessControl",
   "id": "example-bucket/user-jane@gmail.com",
   "selfLink": "https://www.googleapis.com/storage/v1/b/example-bucket/acl/user-jane@gmail.com",
   "bucket": "example-bucket",
   "entity": "user-jane@gmail.com",
   "role": "READER",
   "email": "jane@gmail.com",
   "etag": "CDk="
  },
  {
   "kind": "storage#bucketAccessControl",
   "id": "example-bucket/allUsers",
   "selfLink": "https://www.googleapis.com/storage/v1/b/example-bucket/acl/allUsers",
   "bucket": "example-bucket",
   "entity": "allUsers",
   "role": "READER",
   "etag": "CDk="
  },
  {
   "kind": "storage#bucketAccessControl",
   "id": "example-bucket/allAuthenticatedUsers",
   "selfLink": "https://www.googleapis.com/storage/v1/b/example-bucket/acl/allAuthenticatedUsers",
   "bucket": "example-bucket",
   "entity": "allAuthenticatedUsers",
   "role": "READER",
   "etag": "CDk="
  }
]

XML API

In the XML API, you work with ACLs in XML format. You must attach an XML document to the body of requests to change bucket and object ACLs. An XML document is returned when you get bucket and object ACLs. The XML document contains the individual bucket or object ACL entries.

  • After creating a bucket with a PUT Bucket request, use a second PUT Bucket request with the ?acl parameter to change the bucket ACL.

  • After uploading an object with a PUT Object request, change the ACL with another PUT request using the ?acl parameter or the x-googl-acl request header.

Use the following ACL syntax for the XML API. Note that the RELAX NG Compact Syntax Format Schema describes the exact formatting requirements of the Google ACL XML.

ElementDescription
AccessControlListContainer for Entries and Owner elements.
OwnerContainer for DisplayName and ID elements. This element is not required for objects since an object is always owned by the user who uploaded it. This element is used when you are using Amazon S3 ACL syntax in a migration scenario.

Amazon Simple Storage Service and Amazon S3 are trademarks of Amazon.com, Inc. or its affiliates in the United States and/or other countries.
IDGoogle Cloud Storage ID of the bucket owner.
DisplayNameNot currently implemented. The value is always an empty string.
EntriesContainer for zero or more Entry elements.
EntryContainer for Scope and Permission elements. An Entry must contain only one Scope and one Permission element.
ScopeContainer for an ID, EmailAddress, or Domain element that defines the ACL scope. This element must have a type attribute that contains one of the following values: UserByID, UserByEmail, GroupByID, GroupByEmail, GroupByDomain, AllUsers, or AllAuthenticatedUsers.
IDAn identifier for the grantee when the permission entry is specified by ID.
EmailAddressThe email identifier for the grantee when the permission entry is specified by email.
DomainThe domain identifier for the grantee when the permission entry is specified by domain.
NameOptional element that can be specified or that can be automatically added if the scope is UserByEmail or GroupByEmail.
PermissionThe permission granted READ, WRITE, or FULL_CONTROL.

When working with ACLs using the XML API:

  • You can only use the XML format described above.
  • You cannot set duplicate scopes.

    You can have many entries in your ACL XML, but you cannot have entries with duplicate scopes. For example, you cannot have two entries with the same scope element of jane@example.com.

The following example shows different bucket ACL entries:

<?xml version="1.0" encoding="UTF-8"?>
<AccessControlList>
  <Owner>
    <ID>00b4903a9721...</ID>
  </Owner>
  <Entries>
    <Entry>
      <Scope type="GroupById">
        <ID>00b4903a9722...</ID>
      </Scope>
      <Permission>FULL_CONTROL</Permission>
    </Entry>
    <Entry>
      <Scope type="GroupById">
        <ID>00b4903a9723...</ID>
      </Scope>
      <Permission>FULL_CONTROL</Permission>
    </Entry>
    <Entry>
      <Scope type="GroupById">
        <ID>00b4903a9724...</ID>
      </Scope>
      <Permission>READ</Permission>
    </Entry>
    <Entry>
      <Scope type="GroupByDomain">
        <Domain>example.com</Domain>
      </Scope>
      <Permission>READ</Permission>
    </Entry>
    <Entry>
      <Scope type="GroupByEmail">
        <EmailAddress>gs-announce@googlegroups.com</EmailAddress>
      </Scope>
      <Permission>READ</Permission>
    </Entry>
    <Entry>
      <Scope type="UserByEmail">
        <EmailAddress>jane@gmail.com</EmailAddress>
        <Name>jane</Name>
      </Scope>
      <Permission>READ</Permission>
    </Entry>
    <Entry>
      <Scope type="AllUsers"/>
      <Permission>READ</Permission>
    </Entry>
    <Entry>
      <Scope type="AllAuthenticatedUsers"/>
      <Permission>READ</Permission>
    </Entry>
  </Entries>
</AccessControlList>

Setting the Name element in ACL XML

When you retrieve an ACL from a bucket or object, you might notice an additional <Name> element appended to some of your entries. For example, you might see an entry that looks like the following:

 <Entry>
    <Scope type="UserByEmail">
      <EmailAddress>jane@gmail.com</EmailAddress>
      <Name>Jane</Name>
    </Scope>
    <Permission>FULL_CONTROL</Permission>
 </Entry>

These optional <Name> elements are populated in two circumstances:

  1. When the bucket or object's ACLs include <Name> as an element.

    When you set ACLs, you can choose to include the <Name> element with your ACL entries. You can provide any value in the <Name> element, and Cloud Storage remembers these values until the ACL is removed or overwritten. This approach can be useful if you are using identifiers that aren't easily identifiable, like Google Cloud Storage IDs.

  2. When a UserByEmail or GroupByEmail scope contains a public Google profile.

    If you use either of these scopes but do not provide a <Name> element, Cloud Storage checks if the user or Google Group associated with the email address has a public Google profile with a public name. If so, Cloud Storage automatically populates the <Name> element with the public name.

Applying a predefined ACL

Rather than specifying the entire ACL one entry at a time as shown above, you can use a predefined ACL, which will automatically apply a number of entries customized to a specific scenario. You can apply a predefined ACL to either a bucket or an object by using gsutil, the JSON API, or the XML API.

On new objects

To apply a predefined ACL to an object during object upload:

gsutil

Use the -a option with the gsutil cp command to apply the predefined ACL:

gsutil cp -a [PREDEFINED_ACL] [OBJECT] gs://[BUCKET_NAME]

For example, to apply the predefined ACL bucket-owner-read while uploading an object paris.jpg to a bucket example-travel-maps:

gsutil cp -a bucket-owner-read paris.jpg gs://example-travel-maps

JSON API

Use the predefinedAcl query string parameter in an insert request to apply the prefined ACL.

For example, to apply the predefined ACL bucketOwnerRead while uploading an object paris.jpg to a bucket example-travel-maps:

curl -X POST --data-binary @paris.jpg -H "Content-Type: image/jpeg" \
     -H "Authorization: Bearer ya29.AHES6ZRVmB7fkLtd1XTmq6mo0S1wqZZi3-Lh_s-6Uw7p8vtgSwg"  \
     "https://www.googleapis.com/upload/storage/v1/b/example-travel-maps/o?name=paris.jpg&predefinedAcl=bucketOwnerRead"

The request looks like the following example:

POST /upload/storage/v1/b/example-travel-maps/o?name=paris.jpg&amppredefinedAcl=bucketOwnerRead HTTP/1.1
Host: www.googleapis.com
Content-Type: image/jpeg
Authorization: Bearer ya29.AHES6ZRVmB7fkLtd1XTmq6mo0S1wqZZi3-Lh_s-6Uw7p8vtgSwg
Content-Length: 12345
Date: Fri, 10 Oct 2014 00:02:38 GMT

XML API

Use the x-goog-acl header in a Put Object request to apply the predefined ACL.

For example, to apply the predefined ACL bucket-owner-read while uploading an object paris.jpg to a bucket example-travel-maps:

curl -X PUT --upload-file paris.jpg -H "x-goog-acl: bucket-owner-read" \
     -H "Authorization: Bearer ya29.AHES6ZRVmB7fkLtd1XTmq6mo0S1wqZZi3-Lh_s-6Uw7p8vtgSwg"  \
     https://storage.googleapis.com/example-travel-maps/paris.jpg

The request looks like the following example:

PUT /paris.jpg HTTP/1.1
Host: example-travel-maps.storage.googleapis.com
Date: Thu, 09 Oct 2014 23:06:08 GMT
Content-Length: 12345
Content-Type: image/jpg
x-goog-acl: bucket-owner-read
Authorization: Bearer ya29.AHES6ZRVmB7fkLtd1XTmq6mo0S1wqZZi3-Lh_s-6Uw7p8vtgSwg
 
12345 bytes in entity body

On existing buckets or objects

You can also apply a predefined ACL to an existing bucket or object, which is useful if you want to change from one predefined ACL to another, or you want to update custom ACLs to a predefined ACL.

gsutil

Use the gsutil acl set command to apply the predefined ACL:

gsutil acl set [PREDEFINED_ACL] [OBJECT] gs://[BUCKET_NAME]

For example, to apply the predefined ACL private to the object paris.jpg in the bucket example-travel-maps:

gsutil acl set private gs://example-travel-maps/paris.jpg

JSON API

Use the predefinedAcl query string parameter, and specify an empty acl property in a patch request to apply the prefined ACL.

For example, to apply the predefined ACL private to the object paris.jpg in the bucket example-travel-maps:

curl -X PATCH --data '{"acl": []}'  -H "Content-Type: application/json" \
     -H "Authorization: Bearer ya29.AHES6ZRVmB7fkLtd1XTmq6mo0S1wqZZi3-Lh_s-6Uw7p8vtgSwg"  \
     https://www.googleapis.com/storage/v1/b/example-travel-maps/o/paris.jpg?predefinedAcl=private

The request looks like the following example:

PATCH /storage/v1/b/example-travel-maps/o/paris.jpg?predefinedAcl=private HTTP/1.1
Host: www.googleapis.com
Content-Type: application/json
Authorization: Bearer ya29.AHES6ZRVmB7fkLtd1XTmq6mo0S1wqZZi3-Lh_s-6Uw7p8vtgSwg
Content-Length: 11
Date: Fri, 10 Oct 2014 18:57:59 GMT

XML API

Use the x-goog-acl header with the acl query string parameter in a Put Object request, but do not include an XML document in your request.

For example, to apply the predefined ACL private to the object paris.jpg in the bucket example-travel-maps:

curl -X PUT -H "Content-Length: 0" \
    -H "Authorization: Bearer ya29.AHES6ZRVmB7fkLtd1XTmq6mo0S1wqZZi3-Lh_s-6Uw7p8vtgSwg" \
    -H "x-goog-acl: private" https://storage.googleapis.com/example-travel-maps/paris.jpg?acl

The request looks like the following example:

PUT /paris.jpg?acl HTTP/1.1
Host: example-travel-maps.storage.googleapis.com
Date: Thu, 09 Oct 2014 23:14:59 GMT
Content-Length: 0
x-goog-acl: private
Authorization: Bearer ya29.AHES6ZRVmB7fkLtd1XTmq6mo0S1wqZZi3-Lh_s-6Uw7p8vtgSwg
 
empty entity body

Setting default object ACLs

To avoid setting ACLs every time you create a new object, you can set a default object ACL on a bucket. After you do this, every new object that is added to that bucket that does not explicitly have an ACL applied to it will have the default applied to it. For example, you might want to specify that only a certain group of users have access to most objects in a particular bucket. You can change the default object ACL, and then add objects to the bucket. These added objects have the default object ACL you specfied automatically applied to them; however, you can give specific objects different ACLs, in which case those objects do not have the default ACL applied to them.

To view and change the default object ACL for a bucket:

gsutil

  1. Use gsutil defacl to retrieve the default object ACL:

    gsutil defacl get gs://[BUCKET_NAME]

  2. Use gsutil defacl ch or gsutil defacl set to modify the default object ACL.

    For example, the following command adds jane@gmail.com to the default object ACL for a bucket example-travel-maps:

    gsutil defacl ch -u jane@gmail.com:READER gs://example-travel-maps

    You can also specify the default object ACL from a file. For more information, see the help for gsutil defacl.

Client libraries

C#

For more on installing and creating a Cloud Storage client, refer to Cloud Storage Client Libraries.

The following sample adds a default object ACL to a bucket:

private void AddBucketDefaultOwner(string bucketName, string userEmail)
{
    var storage = StorageClient.Create();
    var bucket = storage.GetBucket(bucketName, new GetBucketOptions()
    {
        Projection = Projection.Full
    });
    if (null == bucket.Acl)
    {
        bucket.Acl = new List<BucketAccessControl>();
    }
    if (null == bucket.DefaultObjectAcl)
    {
        bucket.DefaultObjectAcl = new List<ObjectAccessControl>();
    }
    bucket.DefaultObjectAcl.Add(new ObjectAccessControl()
    {
        Bucket = bucketName,
        Entity = $"user-{userEmail}",
        Role = "OWNER",
    });
    var updatedBucket = storage.UpdateBucket(bucket, new UpdateBucketOptions()
    {
        // Avoid race conditions.
        IfMetagenerationMatch = bucket.Metageneration,
    });
}

The following sample deletes a default object ACL from a bucket:

private void RemoveBucketDefaultOwner(string bucketName, string userEmail)
{
    var storage = StorageClient.Create();
    var bucket = storage.GetBucket(bucketName, new GetBucketOptions()
    {
        Projection = Projection.Full
    });
    if (null == bucket.DefaultObjectAcl)
        return;
    if (null == bucket.Acl)
    {
        bucket.Acl = new List<BucketAccessControl>();
    }
    bucket.DefaultObjectAcl = bucket.DefaultObjectAcl.Where((acl) =>
         !(acl.Entity == $"user-{userEmail}" && acl.Role == "OWNER")
        ).ToList();
    var updatedBucket = storage.UpdateBucket(bucket, new UpdateBucketOptions()
    {
        // Avoid race conditions.
        IfMetagenerationMatch = bucket.Metageneration,
    });
}

Go

For more on installing and creating a Cloud Storage client, refer to Cloud Storage Client Libraries.

The following sample adds a default object ACL to a bucket:

func addDefaultBucketACL(client *storage.Client, bucket string) error {
	ctx := context.Background()

	acl := client.Bucket(bucket).DefaultObjectACL()
	if err := acl.Set(ctx, storage.AllAuthenticatedUsers, storage.RoleReader); err != nil {
		return err
	}
	return nil
}

The following sample deletes a default object ACL from a bucket:

func deleteDefaultBucketACL(client *storage.Client, bucket string) error {
	ctx := context.Background()

	acl := client.Bucket(bucket).DefaultObjectACL()
	if err := acl.Delete(ctx, storage.AllAuthenticatedUsers); err != nil {
		return err
	}
	return nil
}

Java

For more on installing and creating a Cloud Storage client, refer to Cloud Storage Client Libraries.

The following sample adds a default object ACL to a bucket:

Acl acl =
    storage.createDefaultAcl(bucketName, Acl.of(User.ofAllAuthenticatedUsers(), Role.READER));

The following sample deletes a default object ACL from a bucket:

boolean deleted = storage.deleteDefaultAcl(bucketName, User.ofAllAuthenticatedUsers());
if (deleted) {
  // the acl entry was deleted
} else {
  // the acl entry was not found
}

Node.js

For more on installing and creating a Cloud Storage client, refer to Cloud Storage Client Libraries.

The following sample adds a default object ACL to a bucket:

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

// The name of the bucket to access, e.g. "my-bucket"
// const bucketName = "my-bucket";

// The email of the user to add, e.g. "developer@company.com"
// const userEmail = "developer@company.com";

// Instantiates a client
const storage = Storage();

// Makes the user an owner in the default ACL of the bucket. You can use
// addAllUsers(), addDomain(), addProject(), addGroup(), and
// addAllAuthenticatedUsers() to grant access to different types of entities.
// You can also use "readers" and "writers" to grant different roles.
storage
  .bucket(bucketName)
  .acl
  .default
  .owners
  .addUser(userEmail)
  .then(() => {
    console.log(`Added user ${userEmail} as an owner on bucket ${bucketName}.`);
  })
  .catch((err) => {
    console.error('ERROR:', err);
  });

The following sample deletes a default object ACL from a bucket:

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

// The name of the bucket to access, e.g. "my-bucket"
// const bucketName = "my-bucket";

// The email of the user to remove, e.g. "developer@company.com"
// const userEmail = "developer@company.com";

// Instantiates a client
const storage = Storage();

// Removes the user from the access control list of the bucket. You can use
// deleteAllUsers(), deleteDomain(), deleteProject(), deleteGroup(), and
// deleteAllAuthenticatedUsers() to remove access for different types of entities.
storage
  .bucket(bucketName)
  .acl
  .default
  .owners
  .deleteUser(userEmail)
  .then(() => {
    console.log(`Removed user ${userEmail} from bucket ${bucketName}.`);
  })
  .catch((err) => {
    console.error('ERROR:', err);
  });

PHP

For more on installing and creating a Cloud Storage client, refer to Cloud Storage Client Libraries.

The following sample adds a default object ACL to a bucket:

use Google\Cloud\Storage\StorageClient;

/**
 * Add an entity and role to a bucket's default ACL.
 *
 * @param string $bucketName the name of your Cloud Storage bucket.
 * @param string $entity The entity to update access controls for.
 * @param string $role The permissions to add for the specified entity. May
 *        be one of 'OWNER', 'READER', or 'WRITER'.
 * @param array $options
 *
 * @return void
 */
function add_bucket_default_acl($bucketName, $entity, $role, $options = [])
{
    $storage = new StorageClient();
    $bucket = $storage->bucket($bucketName);
    $acl = $bucket->defaultAcl();
    $acl->add($entity, $role, $options);
    printf('Added %s (%s) to gs://%s default ACL' . PHP_EOL, $entity, $role, $bucketName);
}

The following sample deletes a default object ACL from a bucket:

use Google\Cloud\Storage\StorageClient;

/**
 * Delete an entity from a bucket's default ACL.
 *
 * @param string $bucketName the name of your Cloud Storage bucket.
 * @param string $entity the name of the entity to remove from the ACL.
 * @param array $options
 *
 * @return void
 */
function delete_bucket_default_acl($bucketName, $entity, $options = [])
{
    $storage = new StorageClient();
    $bucket = $storage->bucket($bucketName);
    $acl = $bucket->defaultAcl();
    $acl->delete($entity, $options);
    printf('Deleted %s from gs://%s default ACL' . PHP_EOL, $entity, $bucketName);
}

Python

For more on installing and creating a Cloud Storage client, refer to Cloud Storage Client Libraries.

The following sample adds a default object ACL to a bucket:

def add_bucket_default_owner(bucket_name, user_email):
    """Adds a user as an owner in the given bucket's default object access
    control list."""
    storage_client = storage.Client()
    bucket = storage_client.bucket(bucket_name)

    # Reload fetches the current ACL from Cloud Storage.
    bucket.acl.reload()

    # You can also use `group`, `domain`, `all_authenticated` and `all` to
    # grant access to different types of entities. You can also use
    # `grant_read` or `grant_write` to grant different roles.
    bucket.default_object_acl.user(user_email).grant_owner()
    bucket.default_object_acl.save()

    print('Added user {} as an owner in the default acl on bucket {}.'.format(
        user_email, bucket_name))

The following sample deletes a default object ACL from a bucket:

def remove_bucket_default_owner(bucket_name, user_email):
    """Removes a user from the access control list of the given bucket's
    default object access control list."""
    storage_client = storage.Client()
    bucket = storage_client.bucket(bucket_name)

    # Reload fetches the current ACL from Cloud Storage.
    bucket.acl.reload()

    # You can also use `group`, `domain`, `all_authenticated` and `all` to
    # remove access for different types of entities.
    bucket.default_object_acl.user(user_email).revoke_read()
    bucket.default_object_acl.user(user_email).revoke_write()
    bucket.default_object_acl.user(user_email).revoke_owner()
    bucket.default_object_acl.save()

    print('Removed user {} from the default acl of bucket {}.'.format(
        user_email, bucket_name))

Ruby

For more on installing and creating a Cloud Storage client, refer to Cloud Storage Client Libraries.

The following sample adds a default object ACL to a bucket:

# project_id  = "Your Google Cloud project ID"
# bucket_name = "Your Google Cloud Storage bucket name"
# email       = "Google Cloud Storage ACL Entity email"

require "google/cloud/storage"

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

bucket.default_acl.add_owner email

puts "Added default OWNER permission for #{email} to #{bucket_name}"

The following sample deletes a default object ACL from a bucket:

# project_id  = "Your Google Cloud project ID"
# bucket_name = "Your Google Cloud Storage bucket name"
# email       = "Google Cloud Storage ACL Entity email"

require "google/cloud/storage"

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

bucket.default_acl.delete email

puts "Removed default ACL permissions for #{email} from #{bucket_name}"

JSON API

  1. Retrieve the default object ACL with a GET request. For example:

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

  2. Use a patch request to replace the default object ACL. For example, the following request replaces the default object ACL with the ACL specified in defacls.json for a bucket example-travel-maps:

    curl -X PATCH --data @defacls.json -H "Content-Type: application/json" -H "Authorization: Bearer [OAUTH2_TOKEN]" \
        https://www.googleapis.com/storage/v1/b/example-travel-maps

    An example of defacls.json:

    {
     "defaultObjectAcl": [
      {
       "email": "jane@gmail.com",
       "entity": "user-jane@gmail.com",
       "role": "READER"
      }
     ]
    }

XML API

  1. Retrieve the default object ACL with a GET request scoped to your bucket and the ?defaultObjectAcl parameter. For example:

    curl -X GET -H "Authorization: Bearer [OAUTH2_TOKEN]" \
        https://storage.googleapis.com/[BUCKET_NAME]?defaultObjectAcl

  2. Use a PUT request scoped to your bucket with the ?defaultObjectAcl parameter to replace the default object ACL with the ACL specified in acls.xml. For example:

    curl -X PUT --data-binary @acls.xml -H "Authorization: Bearer [OAUTH2_TOKEN]" \
        http://storage.googleapis.com/[BUCKET_NAME]?defaultObjectAcl

    An example of acls.xml:

    <AccessControlList>
      <Entries>
      <Entry>
        <Permission>FULL_CONTROL</Permission>
        <Scope type="GroupByEmail">
          <EmailAddress>travel-companions@googlegroups.com</EmailAddress>
        </Scope>
      </Entry>
      </Entries>
    </AccessControlList>

The syntax of ACLs is discussed in Setting ACLs. You can also specify a predefined ACL as the default object ACL.

To set the default object ACL for a bucket to a predefined ACL:

gsutil

Use the gsutil defacl command with the name of the predefined ACL.

For example, to set the default object ACL to project-private for the bucket example-travel-maps:

gsutil defacl set project-private gs://example-travel-maps

JSON API

Use a PUT request and the predefinedAcl parameter.

For example:

curl -X PUT -H "Content-Length: 0" -H "Authorization: Bearer [OAUTH2_TOKEN]" \
https://www.googleapis.com/storage/v1/b/[BUCKET_NAME]?predefinedAcl=private

XML API

Use a PUT request scoped to your bucket with the ?defaultObjectAcl parameter and the x-goog-acl header.

For example:

curl -X PUT -H "x-goog-acl: project-private" -H "Content-Length: 0" -H "Authorization: Bearer [OAUTH2_TOKEN]" \
http://storage.googleapis.com/[BUCKET_NAME]?defaultObjectAcl

The default object ACLs for a newly created bucket:

To check if a bucket's default object ACL has been modified, compare the bucket's current default object ACL with the default object ACLs for a newly created bucket, which are shown below. Note that the default object ACL for a newly created bucket is equivalent to the predefined projectPrivate ACL.

gsutil

In the example below, the project ID is "123412341234"; your project ID will be different.

[
  {
"entity": "project-owners-123412341234",
"projectTeam": {
  "projectNumber": "123412341234",
  "team": "owners"
},
"role": "OWNER"
  },
  {
"entity": "project-editors-123412341234",
"projectTeam": {
  "projectNumber": "123412341234",
  "team": "editors"
},
"role": "OWNER"
  },
  {
"entity": "project-viewers-123412341234",
"projectTeam": {
  "projectNumber": "123412341234",
  "team": "viewers"
},
"role": "READER"
  }
]

JSON API

In the example below, the project ID is "123412341234"; your project ID will be different.

defaultObjectAcl": [
  {
   "kind": "storage#objectAccessControl",
   "entity": "project-owners-123412341234",
   "role": "OWNER",
   "projectTeam": {
"projectNumber": "123412341234",
"team": "owners"
   }
  },
  {
   "kind": "storage#objectAccessControl",
   "entity": "project-editors-123412341234",
   "role": "OWNER",
   "projectTeam": {
"projectNumber": "123412341234",
"team": "editors"
   }
  },
  {
   "kind": "storage#objectAccessControl",
   "entity": "project-viewers-123412341234",
   "role": "READER",
   "projectTeam": {
"projectNumber": "123412341234",
"team": "viewers"
   }
  }
 ]

XML API

In the example below, the project role IDs start with "00b4903a97..."; your project IDs will be different.

<?xml version='1.0' encoding='UTF-8'?>
<AccessControlList>
  <Entries>
<Entry>
  <Scope type='GroupById'>
    <ID>00b4903a9721...</ID>
  </Scope>
  <Permission>FULL_CONTROL</Permission>
</Entry>
<Entry>
  <Scope type='GroupById'>
    <ID>00b4903a9722...</ID>
  </Scope>
  <Permission>FULL_CONTROL</Permission>
</Entry>
<Entry>
  <Scope type='GroupById'>
    <ID>00b4903a9723...</ID>
  </Scope>
  <Permission>READ</Permission>
</Entry>
  </Entries>
</AccessControlList>

Retrieving ACLs

To get the ACL of an existing bucket or object:

Console

  1. Go to the Cloud Storage browser in the Google Cloud Platform Console.
    Go to the Cloud Storage browser

  2. Navigate to the object whose ACL you want to view.

  3. Choose Edit permissions from the drop down menu for the object.

    You should see a permission dialog with the object's permissions.

gsutil

Use the gsutil acl get to return an object's ACL.

For example, to return the ACL of the object paris.jpg in the bucket example-travel-maps:

gsutil acl get gs://example-travel-maps/paris.jpg

Example response:

[
  {
    "entity": "project-owners-123412341234",
    "projectTeam": {
      "projectNumber": "123412341234",
      "team": "owners"
    },
    "role": "OWNER"
  },
  {
    "entity": "project-editors-123412341234",
    "projectTeam": {
      "projectNumber": "123412341234",
      "team": "editors"
    },
    "role": "OWNER"
  },
  {
    "entity": "project-viewers-123412341234",
    "projectTeam": {
      "projectNumber": "123412341234",
      "team": "viewers"
    },
    "role": "READER"
  },
  {
    "email": "gs-announce@googlegroups.com",
    "entity": "group-gs-announce@googlegroups.com",
    "role": "READER"
  },
  {
    "email": "jane@gmail.com",
    "entity": "user-jane@gmail.com",
    "role": "READER"
  },
  {
    "entity": "allUsers",
    "role": "READER"
  },
  {
    "entity": "allAuthenticatedUsers",
    "role": "READER"
  }
]

To return a bucket's ACL:

gsutil acl get gs://[BUCKET_NAME]

When gsutil returns ACLs for buckets and objects with gsutil acl get, they are in the same JSON format that you can use to set ACLs. ACLs in JSON format use the JSON API property names, such as entity and role.

See the JSON API syntax for more information about how to interpret the output or run gsutil help acls.

Client libraries

C#

For more on installing and creating a Cloud Storage client, refer to Cloud Storage Client Libraries.

The following sample gets a bucket ACL:

private void PrintBucketAcl(string bucketName)
{
    var storage = StorageClient.Create();
    var bucket = storage.GetBucket(bucketName, new GetBucketOptions()
    {
        Projection = Projection.Full
    });
    if (bucket.Acl != null)
        foreach (var acl in bucket.Acl)
        {
            Console.WriteLine($"{acl.Role}:{acl.Entity}");
        }
}

The following sample gets an object ACL:

private void PrintObjectAcl(string bucketName, string objectName)
{
    var storage = StorageClient.Create();
    var storageObject = storage.GetObject(bucketName, objectName,
        new GetObjectOptions() { Projection = Projection.Full });
    if (storageObject.Acl != null)
    {
        foreach (var acl in storageObject.Acl)
        {
            Console.WriteLine($"{acl.Role}:{acl.Entity}");
        }
    }
}

Go

For more on installing and creating a Cloud Storage client, refer to Cloud Storage Client Libraries.

The following sample gets a bucket ACL:

func bucketACL(client *storage.Client, bucket string) error {
	ctx := context.Background()

	rules, err := client.Bucket(bucket).ACL().List(ctx)
	if err != nil {
		return err
	}
	for _, rule := range rules {
		fmt.Printf("ACL rule: %v\n", rule)
	}
	return nil
}

The following sample gets an object ACL:

func objectACL(client *storage.Client, bucket, object string) error {
	ctx := context.Background()

	rules, err := client.Bucket(bucket).Object(object).ACL().List(ctx)
	if err != nil {
		return err
	}
	for _, rule := range rules {
		fmt.Printf("ACL rule: %v\n", rule)
	}
	return nil
}

Java

For more on installing and creating a Cloud Storage client, refer to Cloud Storage Client Libraries.

The following sample gets a bucket ACL:

Acl acl = storage.getAcl(bucketName, User.ofAllAuthenticatedUsers());

The following sample gets an object ACL:

BlobId blobId = BlobId.of(bucketName, blobName, blobGeneration);
Acl acl = storage.getAcl(blobId, User.ofAllAuthenticatedUsers());

Node.js

For more on installing and creating a Cloud Storage client, refer to Cloud Storage Client Libraries.

The following sample gets a bucket ACL:

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

// The name of the bucket to access, e.g. "my-bucket"
// const bucketName = "my-bucket";

// Instantiates a client
const storage = Storage();

// Gets the ACL for the bucket
storage
  .bucket(bucketName)
  .acl
  .get()
  .then((results) => {
    const acls = results[0];

    acls.forEach((acl) => {
      console.log(`${acl.role}: ${acl.entity}`);
    });
  })
  .catch((err) => {
    console.error('ERROR:', err);
  });

The following sample gets an object ACL:

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

// The name of the bucket to access, e.g. "my-bucket"
// const bucketName = "my-bucket";

// The name of the file to access, e.g. "file.txt"
// const filename = "file.txt";

// Instantiates a client
const storage = Storage();

// Gets the ACL for the file
storage
  .bucket(bucketName)
  .file(filename)
  .acl
  .get()
  .then((results) => {
    const acls = results[0];

    acls.forEach((acl) => {
      console.log(`${acl.role}: ${acl.entity}`);
    });
  })
  .catch((err) => {
    console.error('ERROR:', err);
  });

PHP

For more on installing and creating a Cloud Storage client, refer to Cloud Storage Client Libraries.

The following sample gets a bucket ACL:

use Google\Cloud\Storage\StorageClient;

/**
 * Print all entities and roles for a bucket's ACL.
 *
 * @param string $bucketName the name of your Cloud Storage bucket.
 *
 * @return Google\Cloud\Storage\Acl the ACL for the Cloud Storage bucket.
 */
function get_bucket_acl($bucketName)
{
    $storage = new StorageClient();
    $bucket = $storage->bucket($bucketName);
    $acl = $bucket->acl();
    foreach ($acl->get() as $item) {
        printf('%s: %s' . PHP_EOL, $item['entity'], $item['role']);
    }
}

The following sample gets an object ACL:

use Google\Cloud\Storage\StorageClient;

/**
 * Print all entities and roles for an object's ACL.
 *
 * @param string $bucketName the name of your Cloud Storage bucket.
 * @param string $objectName the name of your Cloud Storage object.
 *
 * @return void
 */
function get_object_acl($bucketName, $objectName)
{
    $storage = new StorageClient();
    $bucket = $storage->bucket($bucketName);
    $object = $bucket->object($objectName);
    $acl = $object->acl();
    foreach ($acl->get() as $item) {
        printf('%s: %s' . PHP_EOL, $item['entity'], $item['role']);
    }
}

Python

For more on installing and creating a Cloud Storage client, refer to Cloud Storage Client Libraries.

The following sample gets a bucket ACL:

def print_bucket_acl(bucket_name):
    """Prints out a bucket's access control list."""
    storage_client = storage.Client()
    bucket = storage_client.bucket(bucket_name)

    for entry in bucket.acl:
        print('{}: {}'.format(entry['role'], entry['entity']))

The following sample gets an object ACL:

def print_blob_acl(bucket_name, blob_name):
    """Prints out a blob's access control list."""
    storage_client = storage.Client()
    bucket = storage_client.bucket(bucket_name)
    blob = bucket.blob(blob_name)

    for entry in blob.acl:
        print('{}: {}'.format(entry['role'], entry['entity']))

Ruby

For more on installing and creating a Cloud Storage client, refer to Cloud Storage Client Libraries.

The following sample gets a bucket ACL:

# project_id  = "Your Google Cloud project ID"
# bucket_name = "Your Google Cloud Storage bucket name"

require "google/cloud/storage"

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

puts "ACL for #{bucket_name}:"

bucket.acl.owners.each do |owner|
  puts "OWNER #{owner}"
end

bucket.acl.writers.each do |writer|
  puts "WRITER #{writer}"
end

bucket.acl.readers.each do |reader|
  puts "READER #{reader}"
end

The following sample gets an object ACL:

# project_id  = "Your Google Cloud project ID"
# bucket_name = "Your Google Cloud Storage bucket name"
# file_name   = "Name of a file in the Storage bucket"
# email       = "Google Cloud Storage ACL Entity email"

require "google/cloud/storage"

storage = Google::Cloud::Storage.new project: project_id
bucket  = storage.bucket bucket_name
file    = bucket.file file_name

puts "ACL for #{file_name} in #{bucket_name}:"

file.acl.owners.each do |owner|
  puts "OWNER #{owner}"
end

file.acl.readers.each do |reader|
  puts "READER #{reader}"
end

JSON API

  1. Make sure that you have OWNER permission on the bucket or object.

  2. Retrieve the bucket or object's ACL with a GET request.

    The object ACL is returned in JSON format, attached to the body of the response.

For example, to return the ACL for the object paris.jpg in the bucket example-travel-maps:

curl -X GET -H "Authorization: Bearer ya29.AHES6ZRVmB7fkLtd1XTmq6mo0S1wqZZi3-Lh_s-6Uw7p8vtgSwg" \
 https://www.googleapis.com/storage/v1/b/example-travel-maps/o/paris.jpg?projection=full

You should see a response that looks like:

{
 "kind": "storage#object",
 "id": "example-travel-maps/paris.jpg/1412805837131000",
 "selfLink": "https://www.googleapis.com/storage/v1/b/example-travel-maps/o/paris.jpg",
 "name": "paris.jpg",
 "bucket": "example-travel-maps",
 ...
 "acl": [
  {
   ...
   "entity": "project-owners-867489160491",
   "role": "OWNER",
   "projectTeam": {
    "projectNumber": "867489160491",
    "team": "owners"
   },
   ...
  },
  {
   ...
   "entity": "user-jane@gmail.com",
   "role": "OWNER",
   "email": "jane@gmail.com",
   ...
  },
  {
   ...
   "entity": "group-gs-announce@googlegroups.com",
   "role": "READER",
   "email": "gs-announce@googlegroups.com",
   ...
  }
 ],
 "owner": {
  "entity": "user-jane@gmail.com"
 },
 ...
}

You can also use the objectAccessControls resource GET method to return individual entries in an object's ACL.

XML API

  1. Make sure that you have FULL_CONTROL permission on the bucket or object.

  2. Retrieve the bucket or object's ACL by using the acl query string parameter in a GET Object request.

The ACLs are described in XML, attached to the body of the response.

For example, to return the ACL for the object paris.jpg in the bucket example-travel-maps:

curl -X GET -H "Authorization: Bearer ya29.AHES6ZRVmB7fkLtd1XTmq6mo0S1wqZZi3-Lh_s-6Uw7p8vtgSwg" \
 https://storage.googleapis.com/example-travel-maps/paris.jpg?acl

You should see a response that looks like:

<?xml version="1.0" encoding="UTF-8"?>
<AccessControlList>
  <Owner>
<ID>84fac329bceSAMPLE777d5d22b8SAMPLE77d85ac2SAMPLE2dfcf7c4adf34da46</ID>
<Name>Owner Name</Name>
  </Owner>
  <Entries>
<Entry>
  <Scope type="UserById">
    <ID>84fac329bceSAMPLE777d5d22b8SAMPLE77d85ac2SAMPLE2dfcf7c4adf34da46</ID>
    <Name>Name</Name>
  </Scope>
  <Permission>FULL_CONTROL</Permission>
</Entry>
<Entry>
  <Scope type="UserByEmail">
    <EmailAddress>jane@gmail.com</EmailAddress>
    <Name>Jane</Name>
  </Scope>
  <Permission>FULL_CONTROL</Permission>
</Entry>
<Entry>
  <Scope type="GroupByEmail">
    <EmailAddress>gs-announce@googlegroups.com</EmailAddress>
  </Scope>
  <Permission>READ</Permission>
</Entry>
  </Entries>
</AccessControlList>

You can also use the JSON GET method of the ObjectAccessControls resource to return a specific ACL entry.

Changing ACLs

To change the ACL of an existing object or bucket:

Console

  1. Go to the Cloud Storage browser in the Google Cloud Platform Console.
    Go to the Cloud Storage browser

  2. Navigate to the object whose ACL you want to change.

  3. Choose Edit permissions from the drop down menu for the object.

    You should see a permission dialog with the object's permissions.

The following example shows how to grant the jane@gmail.com user OWNER permission and the members of the gs-announce group READER permission on the object paris.jpg:

Setting ACL on object paris.jpg.

gsutil

  1. Define the ACLs in a file.

  2. Pass the ACLs file to gsutil acl set, and specify the object to set the ACLs on.

For example, to apply the ACLs from the file acls.txt on an object named paris.jpg in the bucket example-travel-maps:

gsutil acl set acl.txt gs://example-travel-maps/paris.jpg

The contents of acl.txt are shown below. These ACLs grant the owners of project 867489160491 along with the user jane@gmail.com OWNER permission for the object paris.jpg, and they grant the members of the gs-announce group READER permission for this object:

[
  {
   "entity": "project-owners-867489160491",
   "role": "OWNER",
   "projectTeam": {
    "projectNumber": "867489160491",
    "team": "owners"
   },
  },
  {
   "entity": "user-jane@gmail.com",
   "email": "jane@gmail.com",
   "role": "OWNER"
  },
  {
   "entity": "group-gs-announce@googlegroups.com",
   "email": "gs-announce@googlegroups.com",
   "role": "READER"
  }
]

You can also set the same ACL for this object with individual grants. For example, to grant the jane@gmail.com user READER access use:

gsutil acl ch -u jane@gmail.com:READ gs://example-travel-maps/paris.jpg
.

Client libraries

C#

For more on installing and creating a Cloud Storage client, refer to Cloud Storage Client Libraries.

The following sample removes an ACL from a bucket:

private void RemoveBucketOwner(string bucketName, string userEmail)
{
    var storage = StorageClient.Create();
    var bucket = storage.GetBucket(bucketName, new GetBucketOptions()
    {
        Projection = Projection.Full
    });
    if (null == bucket.Acl)
        return;
    bucket.Acl = bucket.Acl.Where((acl) =>
        !(acl.Entity == $"user-{userEmail}" && acl.Role == "OWNER")
        ).ToList();
    var updatedBucket = storage.UpdateBucket(bucket, new UpdateBucketOptions()
    {
        // Avoid race conditions.
        IfMetagenerationMatch = bucket.Metageneration,
    });
}

The following sample removes an ACL from an object:

private void RemoveObjectOwner(string bucketName, string objectName,
    string userEmail)
{
    var storage = StorageClient.Create();
    var storageObject = storage.GetObject(bucketName, objectName,
        new GetObjectOptions() { Projection = Projection.Full });
    if (null == storageObject.Acl)
        return;
    storageObject.Acl = storageObject.Acl.Where((acl) =>
        !(acl.Entity == $"user-{userEmail}" && acl.Role == "OWNER")
        ).ToList();
    var updatedObject = storage.UpdateObject(storageObject, new UpdateObjectOptions()
    {
        // Avoid race conditions.
        IfMetagenerationMatch = storageObject.Metageneration,
    });
}

Go

For more on installing and creating a Cloud Storage client, refer to Cloud Storage Client Libraries.

The following sample removes an ACL from a bucket:

func deleteBucketACL(client *storage.Client, bucket string) error {
	ctx := context.Background()

	acl := client.Bucket(bucket).ACL()
	if err := acl.Delete(ctx, storage.AllAuthenticatedUsers); err != nil {
		return err
	}
	return nil
}

The following sample removes an ACL from an object:

func deleteObjectACL(client *storage.Client, bucket, object string) error {
	ctx := context.Background()

	acl := client.Bucket(bucket).Object(object).ACL()
	if err := acl.Delete(ctx, storage.AllAuthenticatedUsers); err != nil {
		return err
	}
	return nil
}

Java

For more on installing and creating a Cloud Storage client, refer to Cloud Storage Client Libraries.

The following sample removes an ACL from a bucket:

boolean deleted = storage.deleteAcl(bucketName, User.ofAllAuthenticatedUsers());
if (deleted) {
  // the acl entry was deleted
} else {
  // the acl entry was not found
}

The following sample removes an ACL from an object:

BlobId blobId = BlobId.of(bucketName, blobName, blobGeneration);
boolean deleted = storage.deleteAcl(blobId, User.ofAllAuthenticatedUsers());
if (deleted) {
  // the acl entry was deleted
} else {
  // the acl entry was not found
}

Node.js

For more on installing and creating a Cloud Storage client, refer to Cloud Storage Client Libraries.

The following sample removes an ACL from a bucket::

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

// The name of the bucket to access, e.g. "my-bucket"
// const bucketName = "my-bucket";

// The email of the user to remove, e.g. "developer@company.com"
// const userEmail = "developer@company.com";

// Instantiates a client
const storage = Storage();

// Removes the user from the access control list of the bucket. You can use
// deleteAllUsers(), deleteDomain(), deleteProject(), deleteGroup(), and
// deleteAllAuthenticatedUsers() to remove access for different types of entities.
storage
  .bucket(bucketName)
  .acl
  .owners
  .deleteUser(userEmail)
  .then(() => {
    console.log(`Removed user ${userEmail} from bucket ${bucketName}.`);
  })
  .catch((err) => {
    console.error('ERROR:', err);
  });

The following sample removes an ACL from an object:

function removeFileOwner (bucketName, filename, userEmail) {
  // Imports the Google Cloud client library
  const Storage = require('@google-cloud/storage');

  // The name of the bucket to access, e.g. "my-bucket"
  // const bucketName = "my-bucket";

  // The name of the file to access, e.g. "file.txt"
  // const filename = "file.txt";

  // The email of the user to remove, e.g. "developer@company.com"
  // const userEmail = "developer@company.com";

  // Instantiates a client
  const storage = Storage();

  // Removes the user from the access control list of the file. You can use
  // deleteAllUsers(), deleteDomain(), deleteProject(), deleteGroup(), and
  // deleteAllAuthenticatedUsers() to remove access for different types of entities.
  storage
    .bucket(bucketName)
    .file(filename)
    .acl
    .owners
    .deleteUser(userEmail)
    .then(() => {
      console.log(`Removed user ${userEmail} from file ${filename}.`);
    })
    .catch((err) => {
      console.error('ERROR:', err);
    });
}

PHP

For more on installing and creating a Cloud Storage client, refer to Cloud Storage Client Libraries.

The following sample removes an ACL from a bucket:

use Google\Cloud\Storage\StorageClient;

/**
 * Delete an entity from a bucket's default ACL.
 *
 * @param string $bucketName the name of your Cloud Storage bucket.
 * @param string $entity the name of the entity to remove from the ACL.
 * @param array $options
 *
 * @return void
 */
function delete_bucket_acl($bucketName, $entity, $options = [])
{
    $storage = new StorageClient();
    $bucket = $storage->bucket($bucketName);
    $acl = $bucket->acl();
    $acl->delete($entity, $options);
    printf('Deleted %s from gs://%s ACL' . PHP_EOL, $entity, $bucketName);
}

The following sample removes an ACL from an object:

use Google\Cloud\Storage\StorageClient;

/**
 * Delete an entity from an object's ACL.
 *
 * @param string $bucketName the name of your Cloud Storage bucket.
 * @param string $objectName the name of your Cloud Storage object.
 * @param string $entity The entity to update access controls for.
 * @param array $options
 *
 * @return void
 */
function delete_object_acl($bucketName, $objectName, $entity, $options = [])
{
    $storage = new StorageClient();
    $bucket = $storage->bucket($bucketName);
    $object = $bucket->object($objectName);
    $acl = $object->acl();
    $acl->delete($entity, $options);
    printf('Deleted %s from gs://%s/%s ACL' . PHP_EOL, $entity, $bucketName, $objectName);
}

Python

For more on installing and creating a Cloud Storage client, refer to Cloud Storage Client Libraries.

The following sample removes an ACL from a bucket:

def remove_bucket_owner(bucket_name, user_email):
    """Removes a user from the access control list of the given bucket."""
    storage_client = storage.Client()
    bucket = storage_client.bucket(bucket_name)

    # Reload fetches the current ACL from Cloud Storage.
    bucket.acl.reload()

    # You can also use `group`, `domain`, `all_authenticated` and `all` to
    # remove access for different types of entities.
    bucket.acl.user(user_email).revoke_read()
    bucket.acl.user(user_email).revoke_write()
    bucket.acl.user(user_email).revoke_owner()
    bucket.acl.save()

    print('Removed user {} from bucket {}.'.format(
        user_email, bucket_name))

The following sample removes an ACL from an object:

def remove_blob_owner(bucket_name, blob_name, user_email):
    """Removes a user from the access control list of the given blob in the
    given bucket."""
    storage_client = storage.Client()
    bucket = storage_client.bucket(bucket_name)
    blob = bucket.blob(blob_name)

    # You can also use `group`, `domain`, `all_authenticated` and `all` to
    # remove access for different types of entities.
    blob.acl.user(user_email).revoke_read()
    blob.acl.user(user_email).revoke_write()
    blob.acl.user(user_email).revoke_owner()
    blob.acl.save()

    print('Removed user {} from blob {} in bucket {}.'.format(
        user_email, blob_name, bucket_name))

Ruby

For more on installing and creating a Cloud Storage client, refer to Cloud Storage Client Libraries.

The following sample removes an ACL from a bucket:

# project_id  = "Your Google Cloud project ID"
# bucket_name = "Your Google Cloud Storage bucket name"
# email       = "Google Cloud Storage ACL Entity email"

require "google/cloud/storage"

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

bucket.acl.delete email

puts "Removed ACL permissions for #{email} from #{bucket_name}"

The following sample removes an ACL from an object:

# project_id  = "Your Google Cloud project ID"
# bucket_name = "Your Google Cloud Storage bucket name"
# file_name   = "Name of a file in the Storage bucket"
# email       = "Google Cloud Storage ACL Entity email"

require "google/cloud/storage"

storage = Google::Cloud::Storage.new project: project_id
bucket  = storage.bucket bucket_name
file    = bucket.file file_name

file.acl.delete email

puts "Removed ACL permissions for #{email} from #{file_name}"

JSON API

  1. Define the ACLs in a JSON file.

  2. Send a patch request with the JSON file, and specify the object to set the ACLs on.

For example, the following cURL command applies a JSON payload from the document acls.json to an object named paris.jpg in the bucket example-travel-maps:

curl -X PATCH --data @acls.json -H "Content-Type: application/json" \
 -H "Authorization: Bearer ya29.AHES6ZRVmB7fkLtd1XTmq6mo0S1wqZZi3-Lh_s-6Uw7p8vtgSwg" \
 https://www.googleapis.com/storage/v1/b/example-travel-maps/o/paris.jpg

If the ACL grants the owners of project 867489160491 and the user jane@gmail.com OWNER permission, along with granting the members of the gs-announce group READER permission, then the request looks like the following example:

PATCH /storage/v1/b/example-travel-maps/o/paris.jpg HTTP/1.1
Host: www.googleapis.com
Content-Type: application/json
Authorization: Bearer ya29.AHES6ZRVmB7fkLtd1XTmq6mo0S1wqZZi3-Lh_s-6Uw7p8vtgSwg
Content-Length: 597
Date: Wed, 08 Oct 2014 22:37:58 GMT
{
"acl": [
  {
   "entity": "project-owners-867489160491",
   "role": "OWNER",
   "projectTeam": {
    "projectNumber": "867489160491",
    "team": "owners"
  },
  {
   "entity": "user-jane@gmail.com",
   "role": "OWNER",
   "email": "jane@gmail.com"
  },
  {
   "entity": "group-gs-announce@googlegroups.com",
   "role": "READER",
   "email": "gs-announce@googlegroups.com"
  }
 ]
}

XML API

  1. Define the ACLs in an XML document.

  2. Send a PUT Object request using the acl query string parameter and the corresponding XML document.

The following cURL command applies an XML payload from the document acls.xml to an object named paris.jpg in the bucket example-travel-maps:

curl -X PUT --data-binary @acls.xml \
 -H "Authorization: Bearer ya29.AHES6ZRVmB7fkLtd1XTmq6mo0S1wqZZi3-Lh_s-6Uw7p8vtgSwg" \
 https://storage.googleapis.com/example-travel-maps/paris.jpg?acl

If the ACL grants the jane@gmail.com user FULL_CONTROL permission and the members of the gs-announce group READ permission, then the request looks like the following example:

PUT /paris.jpg?acl HTTP/1.1
Host: example-travel-maps.storage.googleapis.com
Date: Sat, 20 Feb 2010 08:31:08 GMT
Content-Length: 589
Content-Type=application/xml
Authorization: Bearer ya29.AHES6ZRVmB7fkLtd1XTmq6mo0S1wqZZi3-Lh_s-6Uw7p8vtgSwg
 
<?xml version='1.0' encoding='utf-8'?>
<AccessControlList>
  <Owner>
<ID>84fac329bceSAMPLE777d5d22b8SAMPLE77d85ac2SAMPLE2dfcf7c4adf34da46</ID>
  </Owner>
  <Entries>
  <Entry>
<Permission>FULL_CONTROL</Permission>
<Scope type="UserById">
  <ID>84fac329bceSAMPLE777d5d22b8SAMPLE77d85ac2SAMPLE2dfcf7c4adf34da46</ID>
</Scope>
  </Entry>
  <Entry>
<Scope type="UserByEmail">
  <EmailAddress>jane@gmail.com</EmailAddress>
  <Name>Jane</Name>
</Scope>
<Permission>FULL_CONTROL</Permission>
  </Entry>
  <Entry>
<Scope type="GroupByEmail">
  <EmailAddress>gs-announce@googlegroups.com</EmailAddress>
</Scope>
<Permission>READ</Permission>
  </Entry>
  </Entries>
</AccessControlList>

Monitor your resources on the go

Get the Google Cloud Console app to help you manage your projects.

Send feedback about...

Cloud Storage Documentation