Create and manage access control lists (ACLs) Stay organized with collections Save and categorize content based on your preferences.
This page describes how to control access to buckets and objectsusing Access Control Lists (ACLs). ACLs are a mechanism you can use to definewho has access to your buckets and objects, as well as what level of access theyhave.
See theACL overview to learn more about whether you should use ACLs forcontrolling access to your resources.
Required roles
To get the permissions that you need to create and manage ACLs, ask youradministrator to grant you the Storage Admin(roles/storage.admin) IAM role on the bucket thatcontains the objects for which you want to create and manage ACLs.
This predefined role contains the permissions required to create and manageACLs. To see the exact permissions that are required, expand theRequired permissions section:
Required permissions
storage.buckets.getstorage.buckets.list- This permission is only required for using the Google Cloud consoleto perform the tasks on this page.
storage.buckets.setIamPolicystorage.buckets.updatestorage.objects.getstorage.objects.getIamPolicystorage.objects.setIamPolicystorage.objects.update
You can also get these permissions withcustom roles.
For information about granting roles on buckets, seeSet and manage IAM policies on buckets.
Set or modify ACLs
Console
Note: You cannot use the Google Cloud console to set or modify ACLs onbuckets; the Google Cloud console can only be used to set or modify ACLson individual objects.Go to the Cloud Storage browser in the Google Cloud console.
Go to the Cloud Storage browserFrom the list of buckets, click the name of the bucket that containsthe object whose ACL you want to modify.
Click the name of the object for which you want to set or modify ACLs.
ClickEdit access.
A permission dialog with the object's current ACL opens.
Click+ Add entry.
Choose the type ofEntity to give permission to.
Entity specifies the type of thing that's getting the permission(for example a user or a group). Refer toAccess Control Scopesfor a list of supported values forEntity.
Enter a value inName.
Name identifies a specific user, group, or other entity type. RefertoAccess Control Scopes for a list of supported values forName.
Together,Entity andName define who the permission applies to.
Choose a value inAccess.
Access defines the permission that you want to set on the object.Refer toAccess Control Permissions for a list of supported valuesforAccess.
ClickSave.
To learn how to get detailed error information about failed Cloud Storage operations in the Google Cloud console, seeTroubleshooting.
Command line
To add, modify, or remove an individual grant on an object, use theobjects update command with the relevant flag:
gcloud storage objects update gs://BUCKET_NAME/OBJECT_NAMEFLAG
Where:
BUCKET_NAMEis the name of the bucket thatcontains the object that the modification applies to. For example,example-travel-maps.OBJECT_NAMEis the name of the object thatthe modification applies to. For example,paris.jpg.FLAGis one of the following:--add-acl-grant, along with the grant you want to add ormodify. For example,--add-acl-grant=entity=user-jeffersonloveshiking@gmail.com,role=READER.--remove-acl-grant, along with the entity whose access youwant to remove. For example,--remove-acl-grant=user-jeffersonloveshiking@gmail.com.
To replace all ACLs for an object:
Define the ACLs in a JSON- or YAML-formatted file.
For example, the following ACLs grant the
OWNERpermission for theobjectparis.jpgto the owners of project867489160491and the userjeffersonloveshiking@gmail.com, as well as theREADERpermission forparis.jpgto themembers of thegs-announcegroup:[{ "entity": "project-owners-867489160491", "role": "OWNER", "projectTeam": { "projectNumber": "867489160491", "team": "owners" },},{ "entity": "user-jeffersonloveshiking@gmail.com", "email": "jeffersonloveshiking@gmail.com", "role": "OWNER"},{ "entity": "group-gs-announce@googlegroups.com", "email": "gs-announce@googlegroups.com", "role": "READER"}]Use the
objects updatecommand with the--acl-fileflag:gcloud storage objects update gs://BUCKET_NAME/OBJECT_NAME --acl-file=FILE_LOCATION
Where:
BUCKET_NAMEis the name of the bucket thatcontains the object that the ACLs apply to. For example,example-travel-maps.OBJECT_NAMEis the name of the object thatthe ACLs apply to. For example,paris.jpg.FILE_LOCATIONis the local path to thefile that contains the ACLs you've defined. For example,Desktop/acls.json.
Client libraries
For more information, see theCloud StorageC++ API reference documentation. To authenticate to Cloud Storage, set up Application Default Credentials. For more information, seeSet up authentication for client libraries. The following sample adds an ACL to an object: The following sample removes an ACL from an object: For more information, see theCloud StorageC# API reference documentation. To authenticate to Cloud Storage, set up Application Default Credentials. For more information, seeSet up authentication for client libraries. The following sample adds an ACL to an object: The following sample removes an ACL from an object: For more information, see theCloud StorageGo API reference documentation. To authenticate to Cloud Storage, set up Application Default Credentials. For more information, seeSet up authentication for client libraries. The following sample adds an ACL to an object: The following sample removes an ACL from an object: For more information, see theCloud StorageJava API reference documentation. To authenticate to Cloud Storage, set up Application Default Credentials. For more information, seeSet up authentication for client libraries. The following sample adds an ACL to an object: The following sample removes an ACL from an object: For more information, see theCloud StorageNode.js API reference documentation. To authenticate to Cloud Storage, set up Application Default Credentials. For more information, seeSet up authentication for client libraries. The following sample adds an ACL to an object: The following sample removes an ACL from an object: For more information, see theCloud StoragePHP API reference documentation. To authenticate to Cloud Storage, set up Application Default Credentials. For more information, seeSet up authentication for client libraries. The following sample adds an ACL to an object: The following sample removes an ACL from an object: For more information, see theCloud StoragePython API reference documentation. To authenticate to Cloud Storage, set up Application Default Credentials. For more information, seeSet up authentication for client libraries. The following sample adds an ACL to an object: The following sample removes an ACL from an object: For more information, see theCloud StorageRuby API reference documentation. To authenticate to Cloud Storage, set up Application Default Credentials. For more information, seeSet up authentication for client libraries. The following sample adds an ACL to an object: The following sample removes an ACL from an object:C++
namespacegcs=::google::cloud::storage;using::google::cloud::StatusOr;[](gcs::Clientclient,std::stringconst&bucket_name,std::stringconst&object_name,std::stringconst&entity){StatusOr<gcs::ObjectAccessControl>patched_acl=client.CreateObjectAcl(bucket_name,object_name,entity,gcs::ObjectAccessControl::ROLE_OWNER());if(!patched_acl)throwstd::move(patched_acl).status();std::cout <<"ACL entry for " <<patched_acl->entity() <<" in object " <<patched_acl->object() <<" in bucket " <<patched_acl->bucket() <<" is now " <<*patched_acl <<"\n";}namespacegcs=::google::cloud::storage;using::google::cloud::StatusOr;[](gcs::Clientclient,std::stringconst&bucket_name,std::stringconst&object_name,std::stringconst&entity){StatusOr<gcs::ObjectMetadata>original_metadata=client.GetObjectMetadata(bucket_name,object_name,gcs::Projection::Full());if(!original_metadata)throwstd::move(original_metadata).status();std::vector<gcs::ObjectAccessControl>original_acl=original_metadata->acl();autoit=std::find_if(original_acl.begin(),original_acl.end(),[entity](gcs::ObjectAccessControlconst&entry){returnentry.entity()==entity&&entry.role()==gcs::ObjectAccessControl::ROLE_OWNER();});if(it==original_acl.end()){std::cout <<"Could not find entity " <<entity <<" for file " <<object_name <<" with role OWNER in bucket " <<bucket_name <<"\n";return;}gcs::ObjectAccessControlowner=*it;google::cloud::Statusstatus=client.DeleteObjectAcl(bucket_name,object_name,owner.entity());if(!status.ok())throwstd::runtime_error(status.message());std::cout <<"Deleted ACL entry for " <<owner.entity() <<" for file " <<object_name <<" in bucket " <<bucket_name <<"\n";}C#
usingGoogle.Apis.Storage.v1.Data;usingGoogle.Cloud.Storage.V1;usingSystem;publicclassAddFileOwnerSample{publicGoogle.Apis.Storage.v1.Data.ObjectAddFileOwner(stringbucketName="your-unique-bucket-name",stringobjectName="my-file-name",stringuserEmail="dev@iam.gserviceaccount.com"){varstorage=StorageClient.Create();varstorageObject=storage.GetObject(bucketName,objectName,newGetObjectOptions{Projection=Projection.Full});storageObject.Acl.Add(newObjectAccessControl{Bucket=bucketName,Entity=$"user-{userEmail}",Role="OWNER",});varupdatedObject=storage.UpdateObject(storageObject);Console.WriteLine($"Added user { userEmail} as an owner on file { objectName}.");returnupdatedObject;}}usingGoogle.Cloud.Storage.V1;usingSystem;usingSystem.Linq;publicclassRemoveFileOwnerSample{publicvoidRemoveFileOwner(stringbucketName="your-unique-bucket-name",stringobjectName="your-object-name",stringuserEmail="dev@iam.gserviceaccount.com"){varstorage=StorageClient.Create();varstorageObject=storage.GetObject(bucketName,objectName,newGetObjectOptions{Projection=Projection.Full});if(storageObject.Acl==null){Console.WriteLine("No owner to remove");}else{storageObject.Acl=storageObject.Acl.Where((acl)=>!(acl.Entity==$"user-{userEmail}" &&acl.Role=="OWNER")).ToList();varupdatedObject=storage.UpdateObject(storageObject);Console.WriteLine($"Removed user {userEmail} from file {objectName}.");}}}Go
import("context""fmt""cloud.google.com/go/storage")// addFileOwner adds ACL to the specified object.funcaddFileOwner(bucket,objectstring,entitystorage.ACLEntity)error{// bucket := "bucket-name"// object := "object-name"// entity := storage.AllUsersrole:=storage.RoleOwnerctx:=context.Background()client,err:=storage.NewClient(ctx)iferr!=nil{returnfmt.Errorf("storage.NewClient: %w",err)}deferclient.Close()acl:=client.Bucket(bucket).Object(object).ACL()iferr:=acl.Set(ctx,entity,role);err!=nil{returnfmt.Errorf("ACLHandle.Set: %w",err)}returnnil}import("context""fmt""cloud.google.com/go/storage")// removeFileOwner removes default ACL from the given object.funcremoveFileOwner(bucket,objectstring,entitystorage.ACLEntity)error{// bucket := "bucket-name"// object := "object-name"// entity := storage.AllUsersctx:=context.Background()client,err:=storage.NewClient(ctx)iferr!=nil{returnfmt.Errorf("storage.NewClient: %w",err)}deferclient.Close()acl:=client.Bucket(bucket).Object(object).ACL()iferr:=acl.Delete(ctx,entity);err!=nil{returnfmt.Errorf("ACLHandle.Delete: %w",err)}returnnil}Java
importcom.google.cloud.storage.Acl;importcom.google.cloud.storage.Acl.Role;importcom.google.cloud.storage.Acl.User;importcom.google.cloud.storage.Blob;importcom.google.cloud.storage.BlobId;importcom.google.cloud.storage.Storage;importcom.google.cloud.storage.StorageOptions;publicclassAddBlobOwner{publicstaticvoidaddBlobOwner(StringprojectId,StringbucketName,StringuserEmail,StringblobName){// The ID of your GCP project// String projectId = "your-project-id";// The ID of your GCS bucket// String bucketName = "your-unique-bucket-name";// Email of the user you wish to add as a file owner// String userEmail = "someuser@domain.com"// The name of the blob/file that you wish to modify permissions on// String blobName = "your-blob-name";Storagestorage=StorageOptions.newBuilder().setProjectId(projectId).build().getService();Blobblob=storage.get(BlobId.of(bucketName,blobName));AclnewOwner=Acl.of(newUser(userEmail),Role.OWNER);blob.createAcl(newOwner);System.out.println("Added user "+userEmail+" as an owner on blob "+blobName+" in bucket "+bucketName);}}importcom.google.cloud.storage.Acl.User;importcom.google.cloud.storage.Blob;importcom.google.cloud.storage.BlobId;importcom.google.cloud.storage.Storage;importcom.google.cloud.storage.StorageOptions;publicclassRemoveBlobOwner{publicstaticvoidremoveBlobOwner(StringprojectId,StringbucketName,StringuserEmail,StringblobName){// The ID of your GCP project// String projectId = "your-project-id";// The ID of your GCS bucket// String bucketName = "your-unique-bucket-name";// Email of the user you wish to remove as a file owner// String userEmail = "someuser@domain.com"// The name of the blob/file that you wish to modify permissions on// String blobName = "your-blob-name";Storagestorage=StorageOptions.newBuilder().setProjectId(projectId).build().getService();Blobblob=storage.get(BlobId.of(bucketName,blobName));UserownerToRemove=newUser(userEmail);booleansuccess=blob.deleteAcl(ownerToRemove);if(success){System.out.println("Removed user "+userEmail+" as an owner on file "+blobName+" in bucket "+bucketName);}else{System.out.println("User "+userEmail+" was not found");}}}Node.js
/** * TODO(developer): Uncomment the following lines before running the sample. */// The ID of your GCS bucket// const bucketName = 'your-unique-bucket-name';// The name of the file to access// const fileName = 'file.txt';// The email address of the user to add// const userEmail = 'user-email-to-add';// Imports the Google Cloud client libraryconst{Storage}=require('@google-cloud/storage');// Creates a clientconststorage=newStorage();asyncfunctionaddFileOwner(){awaitstorage.bucket(bucketName).file(fileName).acl.owners.addUser(userEmail);console.log(`Added user${userEmail} as an owner on file${fileName}.`);}addFileOwner().catch(console.error);/** * TODO(developer): Uncomment the following lines before running the sample. */// The ID of your GCS bucket// const bucketName = 'your-unique-bucket-name';// The ID of your GCS file// const fileName = 'your-file-name';// The email address of the user to remove// const userEmail = 'user-email-to-remove';// Imports the Google Cloud client libraryconst{Storage}=require('@google-cloud/storage');// Creates a clientconststorage=newStorage();asyncfunctionremoveFileOwner(){// 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.awaitstorage.bucket(bucketName).file(fileName).acl.owners.deleteUser(userEmail);console.log(`Removed user${userEmail} from file${fileName}.`);}removeFileOwner().catch(console.error);PHP
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. * (e.g. 'my-bucket') * @param string $objectName The name of your Cloud Storage object. * (e.g. 'my-object') * @param string $entity The entity for which to update access controls. * (e.g. 'user-example@domain.com') * @param string $role The permissions to add for the specified entity. * (e.g. 'OWNER') */function add_object_acl(string $bucketName, string $objectName, string $entity, string $role): void{ $storage = new StorageClient(); $bucket = $storage->bucket($bucketName); $object = $bucket->object($objectName); $acl = $object->acl(); $acl->add($entity, $role); printf('Added %s (%s) to gs://%s/%s ACL' . PHP_EOL, $entity, $role, $bucketName, $objectName);}use Google\Cloud\Storage\StorageClient;/** * Delete an entity from an object's ACL. * * @param string $bucketName The name of your Cloud Storage bucket. * (e.g. 'my-bucket') * @param string $objectName The name of your Cloud Storage object. * (e.g. 'my-object') * @param string $entity The entity for which to update access controls. * (e.g. 'user-example@domain.com') */function delete_object_acl(string $bucketName, string $objectName, string $entity): void{ $storage = new StorageClient(); $bucket = $storage->bucket($bucketName); $object = $bucket->object($objectName); $acl = $object->acl(); $acl->delete($entity); printf('Deleted %s from gs://%s/%s ACL' . PHP_EOL, $entity, $bucketName, $objectName);}Python
fromgoogle.cloudimportstoragedefadd_blob_owner(bucket_name,blob_name,user_email):"""Adds a user as an owner on the given blob."""# bucket_name = "your-bucket-name"# blob_name = "your-object-name"# user_email = "name@example.com"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))fromgoogle.cloudimportstoragedefremove_blob_owner(bucket_name,blob_name,user_email):"""Removes a user from the access control list of the given blob in the given bucket."""# bucket_name = "your-bucket-name"# blob_name = "your-object-name"# user_email = "name@example.com"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(f"Removed user{user_email} from blob{blob_name} in bucket{bucket_name}.")Ruby
# The ID of your GCS bucket# bucket_name = "your-unique-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.newbucket=storage.bucketbucket_namefile=bucket.filefile_namefile.acl.add_owneremailputs"Added OWNER permission for#{email} to#{file_name}"# The ID of your GCS bucket# bucket_name = "your-unique-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.newbucket=storage.bucketbucket_namefile=bucket.filefile_namefile.acl.deleteemailputs"Removed ACL permissions for#{email} from#{file_name}"
REST APIs
JSON API
When creating an object, you can specify theacl[] property inthe request body or thepredefinedAcl query parameter in aninsertrequest. For an existing object, specify theacl[] property or thepredefinedAcl query parameter in apatch orupdate request.
For the definition of the object ACL property, see theObjectAccessControls resource.
Define the ACLs in a JSON file.
For example, if the ACL grants the owners of project
867489160491and the userjeffersonloveshiking@gmail.comOWNERpermission, along withgranting the members of thegs-announcegroupREADERpermission,then you could have a file namedacls.jsonwith the followingcontent:{"acl": [ { "entity": "project-owners-867489160491", "role": "OWNER", "projectTeam": { "projectNumber": "867489160491", "team": "owners" } }, { "entity": "user-jeffersonloveshiking@gmail.com", "role": "OWNER", "email": "jeffersonloveshiking@gmail.com" }, { "entity": "group-gs-announce@googlegroups.com", "role": "READER", "email": "gs-announce@googlegroups.com" }]}Send apatch request with the JSON file, and specify the objectto set the ACLs on.
For example, the followingcurl command applies a JSON payload fromthe documentacls.json to an object namedparis.jpg in the bucketexample-travel-maps:
curl -X PATCH --data @acls.json -H "Content-Type: application/json" \ -H "Authorization: Bearer $(gcloud auth print-access-token)" \ https://storage.googleapis.com/storage/v1/b/example-travel-maps/o/paris.jpg
XML API
In theXML API, you work with ACLs in XML format. You must attach anXML 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 XMLdocument contains the individual bucket or object ACL entries.
After creating a bucket with a
PUTBucket request, use a secondPUT Bucket request with the?aclparameter to change the bucket ACL.After uploading an object with a
PUTObject request, change the ACLwith another PUT request using the?aclparameter or thex-googl-aclrequest header.
For example, the followingcurl command applies an XML payload fromthe documentacls.xml to an object namedparis.jpg in the bucketexample-travel-maps:
curl -X PUT --data-binary @acls.xml \ -H "Authorization: Bearer $(gcloud auth print-access-token)" \ https://storage.googleapis.com/example-travel-maps/paris.jpg?acl
Use the following ACL syntax for the XML document:
| Element | Description |
|---|---|
AccessControlList | Container forEntries andOwner elements. |
Owner | Container forDisplayName andID 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 amigration 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. |
ID | Cloud Storage ID of the bucket owner. |
DisplayName | Not implemented. The value is always an empty string. |
Entries | Container for zero or moreEntry elements. |
Entry | Container forScope andPermission elements. AnEntry must contain only oneScope and onePermission element. |
Scope | Container for anID,EmailAddress, orDomain element that defines the ACL scope. This element must have atype attribute that contains one of the following values:UserByID,UserByEmail,GroupByID,GroupByEmail,GroupByDomain,AllUsers, orAllAuthenticatedUsers. |
ID | An identifier for the grantee when the permission entry is specified by ID. |
EmailAddress | The email identifier for the grantee when the permission entry is specified by email. |
Domain | The domain identifier for the grantee when the permission entry is specified by domain. |
Name | Optional element that can be specified or that can be automatically added if the scope isUserByEmail orGroupByEmail. |
Permission | The permission grantedREAD,WRITE, orFULL_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 entrieswith duplicate scopes. For example, you cannot have two entries withthe 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="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>jeffersonloveshiking@gmail.com</EmailAddress> <Name>Jefferson</Name> </Scope> <Permission>FULL_CONTROL</Permission> </Entry> <Entry> <Scope type="AllUsers"/> <Permission>READ</Permission> </Entry> <Entry> <Scope type="AllAuthenticatedUsers"/> <Permission>READ</Permission> </Entry> </Entries></AccessControlList>
Set the Name element in ACL XML
When you retrieve an ACL from a bucket or object, you might notice anadditional<Name> element appended to some of your entries. Forexample, you might see an entry that looks like the following:
<Entry> <Scope type="UserByEmail"> <EmailAddress>jeffersonloveshiking@gmail.com</EmailAddress> <Name>Jefferson</Name> </Scope> <Permission>FULL_CONTROL</Permission></Entry>
These optional<Name> elements are populated in two circumstances:
When the bucket or object's ACLs include
<Name>as an element.When you set ACLs, you can choose to include the
<Name>element withyour ACL entries. You can provide any value in the<Name>element, andCloud Storage remembers these values until the ACL is removedor replaced. This approach can be useful if you are using identifiersthat aren't easily identifiable.When a
UserByEmailorGroupByEmailscope 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 emailaddress has a public Google profile with a public name. If so,Cloud Storage automatically populates the<Name>element withthe public name.
Apply a predefined ACL
Rather than specifying the entire ACL one entry at a time as shown above, youcan use apredefined ACL, which will automatically apply a number of entriescustomized to a specific scenario. You can apply a predefined ACL to either abucket or an object by using the Google Cloud CLI, the JSON API, or the XML API.
On new objects
To apply apredefined ACL to an object during object upload:
Console
You cannot apply a predefined ACL using the Google Cloud console. Usegcloud storage instead.
Command line
Use thegcloud storage cp command with the--predefined-aclflag:
gcloud storage cpOBJECT gs://BUCKET_NAME --predefined-acl=PREDEFINED_ACL
For example, to apply the predefined ACLbucketOwnerRead whileuploading an objectparis.jpg to a bucketexample-travel-maps:
gcloud storage cp paris.jpg gs://example-travel-maps --predefined-acl=bucketOwnerRead
REST APIs
JSON API
Use thepredefinedAcl query string parameter in aninsert request toapply the prefined ACL.
For example, to apply the predefined ACLbucketOwnerRead while uploadingan objectparis.jpg to a bucketexample-travel-maps:
curl -X POST --data-binary @paris.jpg -H "Content-Type: image/jpeg" \ -H "Authorization: Bearer $(gcloud auth print-access-token)" \ "https://storage.googleapis.com/upload/storage/v1/b/example-travel-maps/o?name=paris.jpg&predefinedAcl=bucketOwnerRead"
XML API
Use thex-goog-acl header in aPut Object request to apply thepredefined ACL.
For example, to apply the predefined ACLbucket-owner-read whileuploading an objectparis.jpg to a bucketexample-travel-maps:
curl -X PUT --upload-file paris.jpg -H "x-goog-acl: bucket-owner-read" \ -H "Authorization: Bearer $(gcloud auth print-access-token)" \ https://storage.googleapis.com/example-travel-maps/paris.jpg
On existing buckets or objects
You can also apply a predefined ACL to an existing bucket or object, which isuseful if you want to change from one predefined ACL to another, or you wantto update custom ACLs to a predefined ACL.
Console
You cannot apply a predefined ACL using the Google Cloud console. Usegcloud storage instead.
Command line
Use theobjects update command with the--predefined-acl flag:
gcloud storage objects update gs://BUCKET_NAME/OBJECT_NAME --predefined-acl=PREDEFINED_ACL_NAME
For example, to apply the predefined ACLprivate to the objectparis.jpg in the bucketexample-travel-maps:
gcloud storage objects update gs://example-travel-maps/paris.jpg --predefined-acl=private
REST APIs
JSON API
Use thepredefinedAcl query string parameter, and specify an emptyaclproperty in apatch request to apply the prefined ACL.
For example, to apply the predefined ACLprivate to the objectparis.jpg in the bucketexample-travel-maps:
curl -X PATCH --data '{"acl": []}' -H "Content-Type: application/json" \ -H "Authorization: Bearer $(gcloud auth print-access-token)" \ https://storage.googleapis.com/storage/v1/b/example-travel-maps/o/paris.jpg?predefinedAcl=privateXML API
Use thex-goog-acl header with theacl query string parameter in aPut Object request, but don't include an XML document in yourrequest.
For example, to apply the predefined ACLprivate to the objectparis.jpg in the bucketexample-travel-maps:
curl -X PUT -H "Content-Length: 0" \ -H "Authorization: Bearer $(gcloud auth print-access-token)" \ -H "x-goog-acl: private" \ https://storage.googleapis.com/example-travel-maps/paris.jpg?acl
Set default object ACLs
To avoid setting ACLs every time you create a new object, you can set a defaultobject ACL on a bucket. After you do this, every new object that is added tothat bucket that does not explicitly have an ACL applied to it will have thedefault applied to it. For example, you might want to specify that only acertain group of users have access to most objects in a particular bucket. Youcan change the default object ACL, and then add objects to the bucket. Theseadded objects have the default object ACL you specified automatically applied tothem; however, you can give specific objects different ACLs, in which case thoseobjects do not have the default ACL applied to them.
Important: If you change the default object ACL for a bucket, the change maytake time to propagate, and new objects created in the bucket may still getthe old default object ACL for a short period of time (seeConsistency).In order to make sure that new objects created in the bucket get the updateddefault object ACL, you should wait at least 30 seconds between changingthe default object ACL and creating new objects.To view and change the default object ACL for a bucket:
Console
You cannot set default object ACLs using the Google Cloud console. Usegcloud storage instead.
Command line
Use the
buckets describecommand with the--formatflag toretrieve the default object ACL for the bucket:gcloud storage buckets describe gs://BUCKET_NAME --format="default(default_acl)"
Where
BUCKET_NAMEis the name of the bucketwhose default object ACL you want to view. For example,my-bucket.Use the
buckets updatecommand with the desired flag tomodify the default object ACL for the bucket:gcloud storage buckets update gs://BUCKET_NAMEFLAG
Where:
BUCKET_NAMEis the name of the bucketwhose default object ACL you want to modify. For example,my-bucket.FLAGis one of the following:--add-default-object-acl-grantand a grant that you want toadd to the overall default object ACL for the bucket.--default-object-acl-fileand the path to a local file thatdefines a new default object ACL for the bucket.--predefined-default-object-acland the name of a predefinedobject ACL that you want to replace the existing defaultobject ACL for the bucket with.--remove-default-object-acl-grantand an entity that youwant to remove from the overall default object ACL for thebucket.
Client libraries
For more information, see theCloud StorageC++ API reference documentation. To authenticate to Cloud Storage, set up Application Default Credentials. For more information, seeSet up authentication for client libraries. The following sample adds a default object ACL to a bucket: The following sample deletes a default object ACL from a bucket: For more information, see theCloud StorageC# API reference documentation. To authenticate to Cloud Storage, set up Application Default Credentials. For more information, seeSet up authentication for client libraries. The following sample prints the default object ACL for a bucket: The following sample adds a default object ACL to a bucket: The following sample deletes a default object ACL from a bucket: For more information, see theCloud StorageGo API reference documentation. To authenticate to Cloud Storage, set up Application Default Credentials. For more information, seeSet up authentication for client libraries. The following sample adds a default object ACL to a bucket: The following sample deletes a default object ACL from a bucket: For more information, see theCloud StorageJava API reference documentation. To authenticate to Cloud Storage, set up Application Default Credentials. For more information, seeSet up authentication for client libraries. The following sample adds a default object ACL to a bucket: The following sample deletes a default object ACL from a bucket: For more information, see theCloud StorageNode.js API reference documentation. To authenticate to Cloud Storage, set up Application Default Credentials. For more information, seeSet up authentication for client libraries. The following sample adds a default object ACL to a bucket: The following sample deletes a default object ACL from a bucket: For more information, see theCloud StoragePHP API reference documentation. To authenticate to Cloud Storage, set up Application Default Credentials. For more information, seeSet up authentication for client libraries. The following sample adds a default object ACL to a bucket: The following sample deletes a default object ACL from a bucket: For more information, see theCloud StoragePython API reference documentation. To authenticate to Cloud Storage, set up Application Default Credentials. For more information, seeSet up authentication for client libraries. The following sample adds a default object ACL to a bucket: The following sample deletes a default object ACL from a bucket: For more information, see theCloud StorageRuby API reference documentation. To authenticate to Cloud Storage, set up Application Default Credentials. For more information, seeSet up authentication for client libraries. The following sample adds a default object ACL to a bucket: The following sample deletes a default object ACL from a bucket:C++
namespacegcs=::google::cloud::storage;using::google::cloud::StatusOr;[](gcs::Clientclient,std::stringconst&bucket_name,std::stringconst&entity,std::stringconst&role){StatusOr<gcs::ObjectAccessControl>default_object_acl=client.CreateDefaultObjectAcl(bucket_name,entity,role);if(!default_object_acl)throwstd::move(default_object_acl).status();std::cout <<"Role " <<default_object_acl->role() <<" will be granted default to " <<default_object_acl->entity() <<" on any new object created on bucket " <<default_object_acl->bucket() <<"\n" <<"Full attributes: " <<*default_object_acl <<"\n";}namespacegcs=::google::cloud::storage;[](gcs::Clientclient,std::stringconst&bucket_name,std::stringconst&entity){google::cloud::Statusstatus=client.DeleteDefaultObjectAcl(bucket_name,entity);if(!status.ok())throwstd::runtime_error(status.message());std::cout <<"Deleted ACL entry for " <<entity <<" in bucket " <<bucket_name <<"\n";}C#
usingGoogle.Apis.Storage.v1.Data;usingGoogle.Cloud.Storage.V1;usingSystem;usingSystem.Collections.Generic;publicclassPrintBucketDefaultAclSample{publicIEnumerable<ObjectAccessControl>PrintBucketDefaultAcl(stringbucketName="your-unique-bucket-name"){varstorage=StorageClient.Create();varbucket=storage.GetBucket(bucketName,newGetBucketOptions{Projection=Projection.Full});foreach(varaclinbucket.DefaultObjectAcl){Console.WriteLine($"{acl.Role}:{acl.Entity}");}returnbucket.DefaultObjectAcl;}}usingGoogle.Apis.Storage.v1.Data;usingGoogle.Cloud.Storage.V1;usingSystem;publicclassAddBucketDefaultOwnerSample{publicBucketAddBucketDefaultOwner(stringbucketName="your-unique-bucket-name",stringuserEmail="dev@iam.gserviceaccount.com"){varstorage=StorageClient.Create();varbucket=storage.GetBucket(bucketName,newGetBucketOptions{Projection=Projection.Full});bucket.DefaultObjectAcl.Add(newObjectAccessControl{Bucket=bucketName,Entity=$"user-{userEmail}",Role="OWNER",});varupdatedBucket=storage.UpdateBucket(bucket);Console.WriteLine($"Added user {userEmail} as a default owner on bucket {bucketName}.");returnupdatedBucket;}}usingGoogle.Cloud.Storage.V1;usingSystem;usingSystem.Linq;publicclassRemoveBucketDefaultOwnerSample{publicvoidRemoveBucketDefaultOwner(stringbucketName="your-unique-bucket-name",stringuserEmail="user@iam.gserviceaccount.com"){varstorage=StorageClient.Create();varbucket=storage.GetBucket(bucketName,newGetBucketOptions{Projection=Projection.Full});if(bucket.DefaultObjectAcl==null){Console.WriteLine("No default owner to remove");}else{bucket.DefaultObjectAcl=bucket.DefaultObjectAcl.Where(acl=>!(acl.Entity==$"user-{userEmail}" &&acl.Role=="OWNER")).ToList();varupdatedBucket=storage.UpdateBucket(bucket);Console.WriteLine($"Removed user {userEmail} from bucket {bucketName}.");}}}Go
import("context""fmt""cloud.google.com/go/storage")// addBucketDefaultOwner adds default ACL to the specified bucket.funcaddBucketDefaultOwner(bucketstring,entitystorage.ACLEntity)error{// bucket := "bucket-name"// entity := storage.AllUsersrole:=storage.RoleOwnerctx:=context.Background()client,err:=storage.NewClient(ctx)iferr!=nil{returnfmt.Errorf("storage.NewClient: %w",err)}deferclient.Close()acl:=client.Bucket(bucket).DefaultObjectACL()iferr:=acl.Set(ctx,entity,role);err!=nil{returnfmt.Errorf("ACLHandle.Set: %w",err)}returnnil}import("context""fmt""cloud.google.com/go/storage")// deleteDefaultBucketACL removes default ACL from a bucket.funcremoveBucketDefaultOwner(bucketstring,entitystorage.ACLEntity)error{// bucket := "bucket-name"// entity := storage.AllUsersctx:=context.Background()client,err:=storage.NewClient(ctx)iferr!=nil{returnfmt.Errorf("storage.NewClient: %w",err)}deferclient.Close()acl:=client.Bucket(bucket).DefaultObjectACL()iferr:=acl.Delete(ctx,entity);err!=nil{returnfmt.Errorf("ACLHandle.Delete: %w",err)}returnnil}Java
importcom.google.cloud.storage.Acl;importcom.google.cloud.storage.Acl.Role;importcom.google.cloud.storage.Acl.User;importcom.google.cloud.storage.Bucket;importcom.google.cloud.storage.Storage;importcom.google.cloud.storage.StorageOptions;publicclassAddBucketDefaultOwner{publicstaticvoidaddBucketDefaultOwner(StringbucketName,StringuserEmail){// The ID of your GCS bucket// String bucketName = "your-unique-bucket-name";// The email of the user you wish to add as a default owner// String userEmail = "someuser@domain.com"Storagestorage=StorageOptions.newBuilder().build().getService();Bucketbucket=storage.get(bucketName);AclnewDefaultOwner=Acl.of(newUser(userEmail),Role.OWNER);bucket.createDefaultAcl(newDefaultOwner);System.out.println("Added user "+userEmail+" as an owner on "+bucketName);}}importcom.google.cloud.storage.Acl.User;importcom.google.cloud.storage.Bucket;importcom.google.cloud.storage.Storage;importcom.google.cloud.storage.StorageOptions;publicclassRemoveBucketDefaultOwner{publicstaticvoidremoveBucketDefaultOwner(StringbucketName,StringuserEmail){// The ID of your GCS bucket// String bucketName = "your-unique-bucket-name";// The email of the user you wish to remove as a default owner// String userEmail = "someuser@domain.com"Storagestorage=StorageOptions.newBuilder().build().getService();Bucketbucket=storage.get(bucketName);UseruserToRemove=newUser(userEmail);booleansuccess=bucket.deleteDefaultAcl(userToRemove);if(success){System.out.println("Removed user "+userEmail+" as an owner on "+bucketName);}else{System.out.println("User "+userEmail+" was not found");}}}Node.js
/** * TODO(developer): Uncomment the following lines before running the sample. */// The ID of your GCS bucket// const bucketName = 'your-unique-bucket-name';// The email address of the user to add// const userEmail = 'user-email-to-add';// Imports the Google Cloud client libraryconst{Storage}=require('@google-cloud/storage');// Creates a clientconststorage=newStorage();asyncfunctionaddBucketDefaultOwner(){// 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.awaitstorage.bucket(bucketName).acl.default.owners.addUser(userEmail);console.log(`Added user${userEmail} as an owner on bucket${bucketName}.`);}addBucketDefaultOwner().catch(console.error);/** * TODO(developer): Uncomment the following lines before running the sample. */// The ID of your GCS bucket// const bucketName = 'your-unique-bucket-name';// The email address of the user to remove// const userEmail = 'user-email-to-remove';// Imports the Google Cloud client libraryconst{Storage}=require('@google-cloud/storage');// Creates a clientconststorage=newStorage();asyncfunctionremoveBucketDefaultOwner(){// 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.awaitstorage.bucket(bucketName).acl.default.owners.deleteUser(userEmail);console.log(`Removed user${userEmail} from bucket${bucketName}.`);}removeBucketDefaultOwner().catch(console.error);PHP
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. * (e.g. 'my-bucket') * @param string $entity The entity for which to update access controls. * (e.g. 'user-example@domain.com') * @param string $role The permissions to add for the specified entity. * (e.g. 'OWNER') */function add_bucket_default_acl(string $bucketName, string $entity, string $role): void{ $storage = new StorageClient(); $bucket = $storage->bucket($bucketName); $acl = $bucket->defaultAcl(); $acl->add($entity, $role); printf('Added %s (%s) to gs://%s default ACL' . PHP_EOL, $entity, $role, $bucketName);}use Google\Cloud\Storage\StorageClient;/** * Delete an entity from a bucket's default ACL. * * @param string $bucketName The name of your Cloud Storage bucket. * (e.g. 'my-bucket') * @param string $entity The entity for which to update access controls. * (e.g. 'user-example@domain.com') */function delete_bucket_default_acl(string $bucketName, string $entity): void{ $storage = new StorageClient(); $bucket = $storage->bucket($bucketName); $acl = $bucket->defaultAcl(); $acl->delete($entity); printf('Deleted %s from gs://%s default ACL' . PHP_EOL, $entity, $bucketName);}Python
fromgoogle.cloudimportstoragedefadd_bucket_default_owner(bucket_name,user_email):"""Adds a user as an owner in the given bucket's default object access control list."""# bucket_name = "your-bucket-name"# user_email = "name@example.com"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))fromgoogle.cloudimportstoragedefremove_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."""# bucket_name = "your-bucket-name"# user_email = "name@example.com"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(f"Removed user{user_email} from the default acl of bucket{bucket_name}.")Ruby
# The ID of your GCS bucket# bucket_name = "your-unique-bucket-name"# email = "Google Cloud Storage ACL Entity email"require"google/cloud/storage"storage=Google::Cloud::Storage.newbucket=storage.bucketbucket_namebucket.default_acl.add_owneremailputs"Added default OWNER permission for#{email} to#{bucket_name}"# The ID of your GCS bucket# bucket_name = "your-unique-bucket-name"# email = "Google Cloud Storage ACL Entity email"require"google/cloud/storage"storage=Google::Cloud::Storage.newbucket=storage.bucketbucket_namebucket.default_acl.deleteemailputs"Removed default ACL permissions for#{email} from#{bucket_name}"
REST APIs
JSON API
Retrieve the default object ACL with aGET request. For example:
curl -X GET -H "Authorization: Bearer $(gcloud auth print-access-token)" \ https://storage.googleapis.com/storage/v1/b/BUCKET_NAME?projection=full
Use apatch request to replace the default object ACL. Forexample, the following request replaces the default object ACL withthe ACL specified in
defacls.jsonfor a bucketexample-travel-maps:curl -X PATCH --data @defacls.json -H "Content-Type: application/json" -H "Authorization: Bearer $(gcloud auth print-access-token)" \ https://storage.googleapis.com/storage/v1/b/example-travel-maps
An example of
defacls.json:{"defaultObjectAcl": [ { "email": "jeffersonloveshiking@gmail.com", "entity": "user-jeffersonloveshiking@gmail.com", "role": "READER" }]}
XML API
Retrieve the default object ACL with a
GETrequest scoped toyour bucket and the?defaultObjectAclparameter. For example:curl -X GET -H "Authorization: Bearer $(gcloud auth print-access-token)" \ https://storage.googleapis.com/BUCKET_NAME?defaultObjectAcl
Use a
PUTrequest scoped to your bucket with the?defaultObjectAclparameter to replace the default object ACL withthe ACL specified inacls.xml. For example:curl -X PUT --data-binary @acls.xml -H "Authorization: Bearer $(gcloud auth print-access-token)" \ http://storage.googleapis.com/BUCKET_NAME?defaultObjectAcl
An example of
acls.xml:<AccessControlList> <Entries> <Entry> <Permission>
FULL_CONTROL</Permission> <Scope type="UserByEmail"> <EmailAddress>jeffersonloveshiking@gmail.com</EmailAddress> </Scope> </Entry> </Entries></AccessControlList>
The syntax of ACLs is discussed inSetting ACLs.You can also specify apredefined ACL as the default object ACL.
To set the default object ACL for a bucket to a predefined ACL:
Console
You cannot set default object ACLs using the Google Cloud console. Usegcloud storage instead.
Command line
Use thebuckets update command with the--predefined-default-object-acl flag:
gcloud storage buckets update gs://BUCKET_NAME --predefined-default-object-acl=PREDEFINED_ACL
Where:
BUCKET_NAMEis the name of the bucketwhose default object ACL you want to modify. For example,my-bucket.PREDEFINED_ACLis the name of a validpredefined ACL. For example,projectPrivate.
REST APIs
JSON API
Use a PUT request and thepredefinedAcl parameter.
For example:
curl -X PUT -H "Content-Length: 0" -H "Authorization: Bearer $(gcloud auth print-access-token)" \ https://storage.googleapis.com/storage/v1/b/BUCKET_NAME?predefinedAcl=private
XML API
Use aPUT request scoped to your bucket with the?defaultObjectAclparameter and thex-goog-acl header.
For example:
curl -X PUT -H "x-goog-acl: project-private" -H "Content-Length: 0" -H "Authorization: Bearer $(gcloud auth print-access-token)" \ http://storage.googleapis.com/BUCKET_NAME?defaultObjectAcl
Default object ACLs for newly created buckets:
The following examples show the default object ACLs that automatically apply tonewly created buckets when you don't specify your own default object ACLs aspart of the request. To see if your bucket's default object ACLs have beenchanged, compare your bucket's current default object ACLs to the examplesbelow.
Console
You cannot work with default object ACLs using the Google Cloud console.Usegcloud storage instead.
Command line
In the example below, the project ID is "123412341234"; your project IDwill be different.
defaultObjectAcl:– entity: project-owners-123412341234 etag: CAE= kind: storage#objectAccessControl projectTeam: projectNumber: '123412341234' team: owners role: OWNER– entity: project-editors-123412341234 etag: CAE= kind: storage#objectAccessControl projectTeam: projectNumber: '123412341234' team: editors role: OWNER– entity: project-viewers-123412341234 etag: CAE= kind: storage#objectAccessControl projectTeam: projectNumber: '123412341234' team: viewers role: READER
REST APIs
JSON API
In the example below, the project ID is "123412341234"; your project IDwill 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>
Note that the default object ACL for a newly created bucket is equivalent tothe predefinedprojectPrivate ACL.
Retrieving ACLs
To get the ACL of an existing resource:
Console
Note: You cannot use the Google Cloud console to get ACLs on buckets; theConsole can only be used to get ACLs on individual objects.Go to the Cloud Storage browser in the Google Cloud console.
Go to the Cloud Storage browserNavigate to the object whose ACL you want to view.
ChooseEdit access from the drop-down menu for the object.
You should see a permission dialog with the object's permissions.
To learn how to get detailed error information about failed Cloud Storage operations in the Google Cloud console, seeTroubleshooting.
Command line
Use the
objects describecommand with the--formatflag toretrieve an object's ACL:gcloud storage objects describe gs://BUCKET_NAME/OBJECT_NAME --format="default(acl)"
Where:
BUCKET_NAMEis the name of the bucketcontaining the object whose ACL you want to view. For example,my-bucket.OBJECT_NAMEis the name of the objectwhose ACL you want to view. For example,paris.jpg.
Client libraries
For more information, see theCloud StorageC++ API reference documentation. To authenticate to Cloud Storage, set up Application Default Credentials. For more information, seeSet up authentication for client libraries. The following sample gets an object ACL: For more information, see theCloud StorageC# API reference documentation. To authenticate to Cloud Storage, set up Application Default Credentials. For more information, seeSet up authentication for client libraries. The following sample gets an object ACL: For more information, see theCloud StorageGo API reference documentation. To authenticate to Cloud Storage, set up Application Default Credentials. For more information, seeSet up authentication for client libraries. The following sample gets an object ACL: For more information, see theCloud StorageJava API reference documentation. To authenticate to Cloud Storage, set up Application Default Credentials. For more information, seeSet up authentication for client libraries. The following sample gets an object ACL: For more information, see theCloud StorageNode.js API reference documentation. To authenticate to Cloud Storage, set up Application Default Credentials. For more information, seeSet up authentication for client libraries. The following sample gets an object ACL: For more information, see theCloud StoragePHP API reference documentation. To authenticate to Cloud Storage, set up Application Default Credentials. For more information, seeSet up authentication for client libraries. The following sample gets an object ACL: For more information, see theCloud StoragePython API reference documentation. To authenticate to Cloud Storage, set up Application Default Credentials. For more information, seeSet up authentication for client libraries. The following sample gets an object ACL: For more information, see theCloud StorageRuby API reference documentation. To authenticate to Cloud Storage, set up Application Default Credentials. For more information, seeSet up authentication for client libraries. The following sample gets an object ACL:C++
namespacegcs=::google::cloud::storage;using::google::cloud::StatusOr;[](gcs::Clientclient,std::stringconst&bucket_name,std::stringconst&object_name){StatusOr<std::vector<gcs::ObjectAccessControl>>items=client.ListObjectAcl(bucket_name,object_name);if(!items)throwstd::move(items).status();std::cout <<"ACLs for object=" <<object_name <<" in bucket " <<bucket_name <<"\n";for(gcs::ObjectAccessControlconst&acl:*items){std::cout <<acl.role() <<":" <<acl.entity() <<"\n";}}C#
usingGoogle.Apis.Storage.v1.Data;usingGoogle.Cloud.Storage.V1;usingSystem;usingSystem.Collections.Generic;publicclassPrintFileAclSample{publicIEnumerable<ObjectAccessControl>PrintObjectAcl(stringbucketName="your-unique-bucket-name",stringobjectName="your-object-name"){varstorage=StorageClient.Create();varstorageObject=storage.GetObject(bucketName,objectName,newGetObjectOptions{Projection=Projection.Full});foreach(varaclinstorageObject.Acl){Console.WriteLine($"{acl.Role}:{acl.Entity}");}returnstorageObject.Acl;}}Go
import("context""fmt""io""cloud.google.com/go/storage")// printFileACL lists ACL of the specified object.funcprintFileACL(wio.Writer,bucket,objectstring)error{// bucket := "bucket-name"// object := "object-name"ctx:=context.Background()client,err:=storage.NewClient(ctx)iferr!=nil{returnfmt.Errorf("storage.NewClient: %w",err)}deferclient.Close()rules,err:=client.Bucket(bucket).Object(object).ACL().List(ctx)iferr!=nil{returnfmt.Errorf("ACLHandle.List: %w",err)}for_,rule:=rangerules{fmt.Fprintf(w,"ACL rule: %v\n",rule)}returnnil}Java
importcom.google.cloud.storage.Acl;importcom.google.cloud.storage.Blob;importcom.google.cloud.storage.BlobId;importcom.google.cloud.storage.Storage;importcom.google.cloud.storage.StorageOptions;importjava.util.List;publicclassPrintBlobAcl{publicstaticvoidprintBlobAcl(StringbucketName,StringblobName){// The ID to give your GCS bucket// String bucketName = "your-unique-bucket-name";// The name of the blob/file that you wish to view Acls of// String blobName = "your-blob-name";Storagestorage=StorageOptions.newBuilder().build().getService();Blobblob=storage.get(BlobId.of(bucketName,blobName));List<Acl>blobAcls=blob.getAcl();for(Aclacl:blobAcls){// This will give you the role.// See https://cloud.google.com/storage/docs/access-control/lists#permissionsStringrole=acl.getRole().name();// This will give you the Entity type (i.e. User, Group, Project etc.)// See https://cloud.google.com/storage/docs/access-control/lists#scopesStringentityType=acl.getEntity().getType().name();System.out.printf("%s: %s %n",role,entityType);}}}Node.js
/** * TODO(developer): Uncomment the following lines before running the sample. */// The ID of your GCS bucket// const bucketName = 'your-unique-bucket-name';// The ID of your GCS file// const fileName = 'your-file-name';// Imports the Google Cloud client libraryconst{Storage}=require('@google-cloud/storage');// Creates a clientconststorage=newStorage();asyncfunctionprintFileAcl(){// Gets the ACL for the fileconst[acls]=awaitstorage.bucket(bucketName).file(fileName).acl.get();acls.forEach(acl=>{console.log(`${acl.role}:${acl.entity}`);});}printFileAcl().catch(console.error);PHP
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. * (e.g. 'my-bucket') * @param string $objectName The name of your Cloud Storage object. * (e.g. 'my-object') */function get_object_acl(string $bucketName, string $objectName): void{ $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
Ruby
# The ID of your GCS bucket# bucket_name = "your-unique-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.newbucket=storage.bucketbucket_namefile=bucket.filefile_nameputs"ACL for#{file_name} in#{bucket_name}:"file.acl.owners.eachdo|owner|puts"OWNER#{owner}"endfile.acl.readers.eachdo|reader|puts"READER#{reader}"end
REST APIs
JSON API
Make sure that you have
OWNERpermission on the object.Retrieve the object's ACL with a
GETrequest.The object ACL is returned in JSON format, attached to the body ofthe response.
For example, to return the ACL for the objectparis.jpg in the bucketexample-travel-maps:
curl -X GET -H "Authorization: Bearer $(gcloud auth print-access-token)" \ https://storage.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-jeffersonloveshiking@gmail.com", "role": "OWNER", "email": "jeffersonloveshiking@gmail.com", ... }, { ... "entity": "group-gs-announce@googlegroups.com", "role": "READER", "email": "gs-announce@googlegroups.com", ... } ], "owner": { "entity": "user-jeffersonloveshiking@gmail.com" }, ...}You can also use theobjectAccessControls resourceGET method toreturn individual entries in an object's ACL.
XML API
Make sure that you have
FULL_CONTROLpermission on the bucket or object.Retrieve the bucket or object's ACL by using the
aclquery stringparameter in aGET Object request.
The ACLs are described in XML, attached to the body of the response.
For example, to return the ACL for the objectparis.jpg in the bucketexample-travel-maps:
curl -X GET -H "Authorization: Bearer $(gcloud auth print-access-token)" \ 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>jeffersonloveshiking@gmail.com</EmailAddress> <Name>Jefferson</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 JSONGET method of theObjectAccessControlsresource to return a specific ACL entry.
legacyBucket roles).What's next
- Learn more aboutACLs.
- Learn how to simplify your access controlusing uniform bucket-level access.
- Learn aboutbest practices when using ACLs.
Except as otherwise noted, the content of this page is licensed under theCreative Commons Attribution 4.0 License, and code samples are licensed under theApache 2.0 License. For details, see theGoogle Developers Site Policies. Java is a registered trademark of Oracle and/or its affiliates.
Last updated 2026-02-19 UTC.