Set up and view CORS configurations

OverviewConfiguration samples

Cross Origin Resource Sharing (CORS) allows interactions between resourcesfrom different origins, something that is normally prohibited in order toprevent malicious behavior. Use this page to learn how to set a CORSconfiguration on a Cloud Storage bucket and how to view the CORSconfiguration set on a bucket. SeeConfiguration examples for CORS forexample CORS configurations.

Required roles

To get the permissions that you need to set and view the CORS configurationon a bucket, ask your administrator to grant you the Storage Admin(roles/storage.admin) role on the bucket.

This predefined role contains the permissions required to set and view CORSconfigurations. To see the exact permissions that are required, expand theRequired permissions section:

Required permissions

  • storage.buckets.get
  • storage.buckets.update

You can also get these permissions with otherpredefined roles orcustom roles.

For information about granting roles on buckets, seeSet and manage IAM policies on buckets.

Set the CORS configuration on a bucket

You set a CORS configuration on a bucket by specifying information, such as HTTPmethods and originating domains, that identify the types of requests the bucketcan accept.

Use the following steps to set a CORS configuration on your bucket:

Console

You cannot manage CORS using the Google Cloud console. Use thegcloud CLI instead.

Command line

  1. Create a JSON file with theCORS configuration you would like toapply. Seeconfiguration examples for sample JSON files.

  2. Use thegcloud storage buckets update command with the--cors-file flag:

    gcloud storage buckets update gs://BUCKET_NAME --cors-file=CORS_CONFIG_FILE

    Where:

    • BUCKET_NAME is the name of the relevantbucket. For example,my-bucket.
    • CORS_CONFIG_FILE is the path to the JSONfile you created in Step 1.

Client libraries

C++

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 sets a CORS configuration on a bucket:

namespacegcs=::google::cloud::storage;using::google::cloud::StatusOr;[](gcs::Clientclient,std::stringconst&bucket_name,std::stringconst&origin){StatusOr<gcs::BucketMetadata>original=client.GetBucketMetadata(bucket_name);if(!original)throwstd::move(original).status();std::vector<gcs::CorsEntry>cors_configuration;cors_configuration.emplace_back(gcs::CorsEntry{3600,{"GET"},{origin},{"Content-Type"}});StatusOr<gcs::BucketMetadata>patched=client.PatchBucket(bucket_name,gcs::BucketMetadataPatchBuilder().SetCors(cors_configuration),gcs::IfMetagenerationMatch(original->metageneration()));if(!patched)throwstd::move(patched).status();if(patched->cors().empty()){std::cout <<"Cors configuration is not set for bucket "              <<patched->name() <<"\n";return;}std::cout <<"Cors configuration successfully set for bucket "            <<patched->name() <<"\nNew cors configuration: ";for(autoconst&cors_entry:patched->cors()){std::cout <<"\n  " <<cors_entry <<"\n";}}

C#

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 sets a CORS configuration on a bucket:

usingGoogle.Apis.Storage.v1.Data;usingGoogle.Cloud.Storage.V1;usingSystem;usingSystem.Collections.Generic;usingstaticGoogle.Apis.Storage.v1.Data.Bucket;publicclassBucketAddCorsConfigurationSample{publicBucketBucketAddCorsConfiguration(stringbucketName="your-bucket-name"){varstorage=StorageClient.Create();varbucket=storage.GetBucket(bucketName);CorsDatacorsData=newCorsData{Origin=newstring[]{"*"},ResponseHeader=newstring[]{"Content-Type","x-goog-resumable"},Method=newstring[]{"PUT","POST"},MaxAgeSeconds=3600//One Hour};if(bucket.Cors==null){bucket.Cors=newList<CorsData>();}bucket.Cors.Add(corsData);bucket=storage.UpdateBucket(bucket);Console.WriteLine($"bucketName {bucketName} was updated with a CORS config to allow {string.Join(",", corsData.Method)} requests from"+$" {string.Join(",", corsData.Origin)} sharing {string.Join(",", corsData.ResponseHeader)} responseHeader"+$" responses across origins.");returnbucket;}}

Go

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 sets a CORS configuration on a bucket:

import("context""fmt""io""time""cloud.google.com/go/storage")// setBucketCORSConfiguration sets a CORS configuration on a bucket.funcsetBucketCORSConfiguration(wio.Writer,bucketNamestring,maxAgetime.Duration,methods,origins,responseHeaders[]string)error{// bucketName := "bucket-name"// maxAge := time.Hour// methods := []string{"GET"}// origins := []string{"some-origin.com"}// responseHeaders := []string{"Content-Type"}ctx:=context.Background()client,err:=storage.NewClient(ctx)iferr!=nil{returnfmt.Errorf("storage.NewClient: %w",err)}deferclient.Close()ctx,cancel:=context.WithTimeout(ctx,time.Second*10)defercancel()bucket:=client.Bucket(bucketName)bucketAttrsToUpdate:=storage.BucketAttrsToUpdate{CORS:[]storage.CORS{{MaxAge:maxAge,Methods:methods,Origins:origins,ResponseHeaders:responseHeaders,}},}if_,err:=bucket.Update(ctx,bucketAttrsToUpdate);err!=nil{returnfmt.Errorf("Bucket(%q).Update: %w",bucketName,err)}fmt.Fprintf(w,"Bucket %v was updated with a CORS config to allow %v requests from %v sharing %v responses across origins\n",bucketName,methods,origins,responseHeaders)returnnil}

Java

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 sets a CORS configuration on a bucket:

importcom.google.cloud.storage.Bucket;importcom.google.cloud.storage.Cors;importcom.google.cloud.storage.HttpMethod;importcom.google.cloud.storage.Storage;importcom.google.cloud.storage.StorageOptions;importcom.google.common.collect.ImmutableList;publicclassConfigureBucketCors{publicstaticvoidconfigureBucketCors(StringprojectId,StringbucketName,Stringorigin,StringresponseHeader,IntegermaxAgeSeconds){// The ID of your GCP project// String projectId = "your-project-id";// The ID of your GCS bucket// String bucketName = "your-unique-bucket-name";// The origin for this CORS config to allow requests from// String origin = "http://example.appspot.com";// The response header to share across origins// String responseHeader = "Content-Type";// The maximum amount of time the browser can make requests before it must repeat preflighted// requests// Integer maxAgeSeconds = 3600;Storagestorage=StorageOptions.newBuilder().setProjectId(projectId).build().getService();Bucketbucket=storage.get(bucketName);// See the HttpMethod documentation for other HTTP methods available:// https://cloud.google.com/appengine/docs/standard/java/javadoc/com/google/appengine/api/urlfetch/HTTPMethodHttpMethodmethod=HttpMethod.GET;Corscors=Cors.newBuilder().setOrigins(ImmutableList.of(Cors.Origin.of(origin))).setMethods(ImmutableList.of(method)).setResponseHeaders(ImmutableList.of(responseHeader)).setMaxAgeSeconds(maxAgeSeconds).build();bucket.toBuilder().setCors(ImmutableList.of(cors)).build().update();System.out.println("Bucket "+bucketName+" was updated with a CORS config to allow GET requests from "+origin+" sharing "+responseHeader+" responses across origins");}}

Node.js

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 sets a CORS configuration on a bucket:

// Imports the Google Cloud client libraryconst{Storage}=require('@google-cloud/storage');// Creates a clientconststorage=newStorage();/** * TODO(developer): Uncomment the following lines before running the sample. */// The ID of your GCS bucket// const bucketName = 'your-unique-bucket-name';// The origin for this CORS config to allow requests from// const origin = 'http://example.appspot.com';// The response header to share across origins// const responseHeader = 'Content-Type';// The maximum amount of time the browser can make requests before it must// repeat preflighted requests// const maxAgeSeconds = 3600;// The name of the method// See the HttpMethod documentation for other HTTP methods available:// https://cloud.google.com/appengine/docs/standard/java/javadoc/com/google/appengine/api/urlfetch/HTTPMethod// const method = 'GET';asyncfunctionconfigureBucketCors(){awaitstorage.bucket(bucketName).setCorsConfiguration([{maxAgeSeconds,method:[method],origin:[origin],responseHeader:[responseHeader],},]);console.log(`Bucket${bucketName} was updated with a CORS config      to allow${method} requests from${origin} sharing${responseHeader} responses across origins`);}configureBucketCors().catch(console.error);

PHP

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 sets a CORS configuration on a bucket:

use Google\Cloud\Storage\StorageClient;/** * Update the CORS configuration of a bucket. * * @param string $bucketName The name of your Cloud Storage bucket. *        (e.g. 'my-bucket') * @param string $method The HTTP method for the CORS config. (e.g. 'GET') * @param string $origin The origin from which the CORS config will allow requests. *        (e.g. 'http://example.appspot.com') * @param string $responseHeader The response header to share across origins. *        (e.g. 'Content-Type') * @param int $maxAgeSeconds The maximum amount of time the browser can make *        (e.g. 3600) *     requests before it must repeat preflighted requests. */function cors_configuration(string $bucketName, string $method, string $origin, string $responseHeader, int $maxAgeSeconds): void{    $storage = new StorageClient();    $bucket = $storage->bucket($bucketName);    $bucket->update([        'cors' => [            [                'method' => [$method],                'origin' => [$origin],                'responseHeader' => [$responseHeader],                'maxAgeSeconds' => $maxAgeSeconds,            ]        ]    ]);    printf(        'Bucket %s was updated with a CORS config to allow GET requests from ' .        '%s sharing %s responses across origins.',        $bucketName,        $origin,        $responseHeader    );}

Python

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 sets a CORS configuration on a bucket:

fromgoogle.cloudimportstoragedefcors_configuration(bucket_name):"""Set a bucket's CORS policies configuration."""# bucket_name = "your-bucket-name"storage_client=storage.Client()bucket=storage_client.get_bucket(bucket_name)bucket.cors=[{"origin":["*"],"responseHeader":["Content-Type","x-goog-resumable"],"method":['PUT','POST'],"maxAgeSeconds":3600}]bucket.patch()print(f"Set CORS policies for bucket{bucket.name} is{bucket.cors}")returnbucket

Ruby

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 sets a CORS configuration on a bucket:

defcors_configurationbucket_name:# The ID of your GCS bucket# bucket_name = "your-unique-bucket-name"require"google/cloud/storage"storage=Google::Cloud::Storage.newbucket=storage.bucketbucket_namebucket.corsdo|c|c.add_rule["*"],["PUT","POST"],headers:["Content-Type","x-goog-resumable"],max_age:3600endputs"Set CORS policies for bucket#{bucket_name}"end

REST APIs

JSON API

  1. Have gcloud CLIinstalled and initialized, which lets you generate an access token for theAuthorization header.

  2. Create a JSON file with theCORS configuration you would liketo apply. Seeconfiguration examples for sample JSON files.

  3. UsecURL to call theJSON API with aPATCH Bucket request:

    curl--requestPATCH\'https://storage.googleapis.com/storage/v1/b/BUCKET_NAME?fields=cors' \--header'Authorization:Bearer$(gcloudauthprint-access-token)'\--header'Content-Type:application/json'\--data-binary@CORS_CONFIG_FILE

    Where:

    • BUCKET_NAME is the name of the bucket. Forexample,my-bucket.
    • CORS_CONFIG_FILE is the path to the JSONfile you created in Step 2.

XML API

  1. Have gcloud CLIinstalled and initialized, which lets you generate an access token for theAuthorization header.

  2. Create a XML file with theCORS configuration you would liketo apply. Seeconfiguration examples for sample XML files.

  3. UsecURL to call theXML API with aPUT Bucket request scoped to?cors:

    curl-XPUT--data-binary@CORS_CONFIG_FILE\-H"Authorization:Bearer$(gcloudauthprint-access-token)"\-H"x-goog-project-id:PROJECT_ID"\"https://storage.googleapis.com/BUCKET_NAME?cors"

    Where:

    • BUCKET_NAME is the name of the bucket. Forexample,my-bucket.
    • PROJECT_ID is the ID of the projectassociated with the bucket. For example,my-project.
    • CORS_CONFIG_FILE is the path to the XMLfile you created in Step 2.
Note: When creating a CORS configuration, you canspecify multiple origins, headers, and methods.

View the CORS configuration for a bucket

To view the CORS configuration for a bucket:

Console

You cannot manage CORS using the Google Cloud console. Use thegcloud CLI instead.

Command line

Note: To change the output formatting from YAML (default) to another format,seeFiltering and formatting output for instructions.

Use thegcloud storage buckets describe command with the--format flag:

gcloud storage buckets describe gs://BUCKET_NAME --format="default(cors_config)"

WhereBUCKET_NAME is the name of the bucketwhose CORS configuration you want to view. For example,my-bucket.

Client libraries

To view the CORS configuration for a bucket using the client libraries,follow the instructions for displaying a bucket's metadata and look for theCORS field in the response:

C++

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.

namespacegcs=::google::cloud::storage;using::google::cloud::StatusOr;[](gcs::Clientclient,std::stringconst&bucket_name){StatusOr<gcs::BucketMetadata>bucket_metadata=client.GetBucketMetadata(bucket_name);if(!bucket_metadata)throwstd::move(bucket_metadata).status();std::cout <<"The metadata for bucket " <<bucket_metadata->name() <<" is "            <<*bucket_metadata <<"\n";}

C#

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.

usingGoogle.Apis.Storage.v1.Data;usingGoogle.Cloud.Storage.V1;usingSystem;publicclassGetBucketMetadataSample{publicBucketGetBucketMetadata(stringbucketName="your-unique-bucket-name"){varstorage=StorageClient.Create();varbucket=storage.GetBucket(bucketName,newGetBucketOptions{Projection=Projection.Full});Console.WriteLine($"Bucket:\t{bucket.Name}");Console.WriteLine($"Acl:\t{bucket.Acl}");Console.WriteLine($"Billing:\t{bucket.Billing}");Console.WriteLine($"Cors:\t{bucket.Cors}");Console.WriteLine($"DefaultEventBasedHold:\t{bucket.DefaultEventBasedHold}");Console.WriteLine($"DefaultObjectAcl:\t{bucket.DefaultObjectAcl}");Console.WriteLine($"Encryption:\t{bucket.Encryption}");if(bucket.Encryption!=null){Console.WriteLine($"KmsKeyName:\t{bucket.Encryption.DefaultKmsKeyName}");}Console.WriteLine($"Id:\t{bucket.Id}");Console.WriteLine($"Kind:\t{bucket.Kind}");Console.WriteLine($"Lifecycle:\t{bucket.Lifecycle}");Console.WriteLine($"Location:\t{bucket.Location}");Console.WriteLine($"LocationType:\t{bucket.LocationType}");Console.WriteLine($"Logging:\t{bucket.Logging}");Console.WriteLine($"Metageneration:\t{bucket.Metageneration}");Console.WriteLine($"ObjectRetention:\t{bucket.ObjectRetention}");Console.WriteLine($"Owner:\t{bucket.Owner}");Console.WriteLine($"ProjectNumber:\t{bucket.ProjectNumber}");Console.WriteLine($"RetentionPolicy:\t{bucket.RetentionPolicy}");Console.WriteLine($"SelfLink:\t{bucket.SelfLink}");Console.WriteLine($"StorageClass:\t{bucket.StorageClass}");Console.WriteLine($"TimeCreated:\t{bucket.TimeCreated}");Console.WriteLine($"Updated:\t{bucket.Updated}");Console.WriteLine($"Versioning:\t{bucket.Versioning}");Console.WriteLine($"Website:\t{bucket.Website}");Console.WriteLine($"TurboReplication:\t{bucket.Rpo}");if(bucket.Labels!=null){Console.WriteLine("Labels:");foreach(varlabelinbucket.Labels){Console.WriteLine($"{label.Key}:\t{label.Value}");}}returnbucket;}}

Go

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.

import("context""fmt""io""time""cloud.google.com/go/storage")// getBucketMetadata gets the bucket metadata.funcgetBucketMetadata(wio.Writer,bucketNamestring)(*storage.BucketAttrs,error){// bucketName := "bucket-name"ctx:=context.Background()client,err:=storage.NewClient(ctx)iferr!=nil{returnnil,fmt.Errorf("storage.NewClient: %w",err)}deferclient.Close()ctx,cancel:=context.WithTimeout(ctx,time.Second*10)defercancel()attrs,err:=client.Bucket(bucketName).Attrs(ctx)iferr!=nil{returnnil,fmt.Errorf("Bucket(%q).Attrs: %w",bucketName,err)}fmt.Fprintf(w,"BucketName: %v\n",attrs.Name)fmt.Fprintf(w,"Location: %v\n",attrs.Location)fmt.Fprintf(w,"LocationType: %v\n",attrs.LocationType)fmt.Fprintf(w,"StorageClass: %v\n",attrs.StorageClass)fmt.Fprintf(w,"Turbo replication (RPO): %v\n",attrs.RPO)fmt.Fprintf(w,"TimeCreated: %v\n",attrs.Created)fmt.Fprintf(w,"Metageneration: %v\n",attrs.MetaGeneration)fmt.Fprintf(w,"PredefinedACL: %v\n",attrs.PredefinedACL)ifattrs.Encryption!=nil{fmt.Fprintf(w,"DefaultKmsKeyName: %v\n",attrs.Encryption.DefaultKMSKeyName)}ifattrs.Website!=nil{fmt.Fprintf(w,"IndexPage: %v\n",attrs.Website.MainPageSuffix)fmt.Fprintf(w,"NotFoundPage: %v\n",attrs.Website.NotFoundPage)}fmt.Fprintf(w,"DefaultEventBasedHold: %v\n",attrs.DefaultEventBasedHold)ifattrs.RetentionPolicy!=nil{fmt.Fprintf(w,"RetentionEffectiveTime: %v\n",attrs.RetentionPolicy.EffectiveTime)fmt.Fprintf(w,"RetentionPeriod: %v\n",attrs.RetentionPolicy.RetentionPeriod)fmt.Fprintf(w,"RetentionPolicyIsLocked: %v\n",attrs.RetentionPolicy.IsLocked)}fmt.Fprintf(w,"ObjectRetentionMode: %v\n",attrs.ObjectRetentionMode)fmt.Fprintf(w,"RequesterPays: %v\n",attrs.RequesterPays)fmt.Fprintf(w,"VersioningEnabled: %v\n",attrs.VersioningEnabled)ifattrs.Logging!=nil{fmt.Fprintf(w,"LogBucket: %v\n",attrs.Logging.LogBucket)fmt.Fprintf(w,"LogObjectPrefix: %v\n",attrs.Logging.LogObjectPrefix)}ifattrs.CORS!=nil{fmt.Fprintln(w,"CORS:")for_,v:=rangeattrs.CORS{fmt.Fprintf(w,"\tMaxAge: %v\n",v.MaxAge)fmt.Fprintf(w,"\tMethods: %v\n",v.Methods)fmt.Fprintf(w,"\tOrigins: %v\n",v.Origins)fmt.Fprintf(w,"\tResponseHeaders: %v\n",v.ResponseHeaders)}}ifattrs.Labels!=nil{fmt.Fprintf(w,"\n\n\nLabels:")forkey,value:=rangeattrs.Labels{fmt.Fprintf(w,"\t%v = %v\n",key,value)}}returnattrs,nil}

Java

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.

importcom.google.cloud.storage.Bucket;importcom.google.cloud.storage.BucketInfo;importcom.google.cloud.storage.Storage;importcom.google.cloud.storage.StorageOptions;importjava.util.Map;publicclassGetBucketMetadata{publicstaticvoidgetBucketMetadata(StringprojectId,StringbucketName){// The ID of your GCP project// String projectId = "your-project-id";// The ID of your GCS bucket// String bucketName = "your-unique-bucket-name";Storagestorage=StorageOptions.newBuilder().setProjectId(projectId).build().getService();// Select all fields. Fields can be selected individually e.g. Storage.BucketField.NAMEBucketbucket=storage.get(bucketName,Storage.BucketGetOption.fields(Storage.BucketField.values()));// Print bucket metadataSystem.out.println("BucketName: "+bucket.getName());System.out.println("DefaultEventBasedHold: "+bucket.getDefaultEventBasedHold());System.out.println("DefaultKmsKeyName: "+bucket.getDefaultKmsKeyName());System.out.println("Id: "+bucket.getGeneratedId());System.out.println("IndexPage: "+bucket.getIndexPage());System.out.println("Location: "+bucket.getLocation());System.out.println("LocationType: "+bucket.getLocationType());System.out.println("Metageneration: "+bucket.getMetageneration());System.out.println("NotFoundPage: "+bucket.getNotFoundPage());System.out.println("RetentionEffectiveTime: "+bucket.getRetentionEffectiveTime());System.out.println("RetentionPeriod: "+bucket.getRetentionPeriod());System.out.println("RetentionPolicyIsLocked: "+bucket.retentionPolicyIsLocked());System.out.println("RequesterPays: "+bucket.requesterPays());System.out.println("SelfLink: "+bucket.getSelfLink());System.out.println("StorageClass: "+bucket.getStorageClass().name());System.out.println("TimeCreated: "+bucket.getCreateTime());System.out.println("VersioningEnabled: "+bucket.versioningEnabled());System.out.println("ObjectRetention: "+bucket.getObjectRetention());if(bucket.getLabels()!=null){System.out.println("\n\n\nLabels:");for(Map.Entry<String,String>label:bucket.getLabels().entrySet()){System.out.println(label.getKey()+"="+label.getValue());}}if(bucket.getLifecycleRules()!=null){System.out.println("\n\n\nLifecycle Rules:");for(BucketInfo.LifecycleRulerule:bucket.getLifecycleRules()){System.out.println(rule);}}}}

Node.js

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.

// Imports the Google Cloud client libraryconst{Storage}=require('@google-cloud/storage');// Creates a clientconststorage=newStorage();asyncfunctiongetBucketMetadata(){/**   * TODO(developer): Uncomment the following lines before running the sample.   */// The ID of your GCS bucket// const bucketName = 'your-unique-bucket-name';// Get Bucket Metadataconst[metadata]=awaitstorage.bucket(bucketName).getMetadata();console.log(JSON.stringify(metadata,null,2));}

PHP

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.

use Google\Cloud\Storage\StorageClient;/** * Get bucket metadata. * * @param string $bucketName The name of your Cloud Storage bucket. *        (e.g. 'my-bucket') */function get_bucket_metadata(string $bucketName): void{    $storage = new StorageClient();    $bucket = $storage->bucket($bucketName);    $info = $bucket->info();    printf('Bucket Metadata: %s' . PHP_EOL, print_r($info, true));}

Python

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.

fromgoogle.cloudimportstoragedefbucket_metadata(bucket_name):"""Prints out a bucket's metadata."""# bucket_name = 'your-bucket-name'storage_client=storage.Client()bucket=storage_client.get_bucket(bucket_name)print(f"ID:{bucket.id}")print(f"Name:{bucket.name}")print(f"Storage Class:{bucket.storage_class}")print(f"Location:{bucket.location}")print(f"Location Type:{bucket.location_type}")print(f"Cors:{bucket.cors}")print(f"Default Event Based Hold:{bucket.default_event_based_hold}")print(f"Default KMS Key Name:{bucket.default_kms_key_name}")print(f"Metageneration:{bucket.metageneration}")print(f"Public Access Prevention:{bucket.iam_configuration.public_access_prevention}")print(f"Retention Effective Time:{bucket.retention_policy_effective_time}")print(f"Retention Period:{bucket.retention_period}")print(f"Retention Policy Locked:{bucket.retention_policy_locked}")print(f"Object Retention Mode:{bucket.object_retention_mode}")print(f"Requester Pays:{bucket.requester_pays}")print(f"Self Link:{bucket.self_link}")print(f"Time Created:{bucket.time_created}")print(f"Versioning Enabled:{bucket.versioning_enabled}")print(f"Labels:{bucket.labels}")

Ruby

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.

defget_bucket_metadatabucket_name:# The ID of your GCS bucket# bucket_name = "your-unique-bucket-name"require"google/cloud/storage"storage=Google::Cloud::Storage.newbucket=storage.bucketbucket_nameputs"ID:#{bucket.id}"puts"Name:#{bucket.name}"puts"Storage Class:#{bucket.storage_class}"puts"Location:#{bucket.location}"puts"Location Type:#{bucket.location_type}"puts"Cors:#{bucket.cors}"puts"Default Event Based Hold:#{bucket.default_event_based_hold?}"puts"Default KMS Key Name:#{bucket.default_kms_key}"puts"Logging Bucket:#{bucket.logging_bucket}"puts"Logging Prefix:#{bucket.logging_prefix}"puts"Metageneration:#{bucket.metageneration}"puts"Retention Effective Time:#{bucket.retention_effective_at}"puts"Retention Period:#{bucket.retention_period}"puts"Retention Policy Locked:#{bucket.retention_policy_locked?}"puts"Requester Pays:#{bucket.requester_pays}"puts"Self Link:#{bucket.api_url}"puts"Time Created:#{bucket.created_at}"puts"Versioning Enabled:#{bucket.versioning?}"puts"Index Page:#{bucket.website_main}"puts"Not Found Page:#{bucket.website_404}"puts"Labels:"bucket.labels.eachdo|key,value|puts" -#{key} =#{value}"endputs"Lifecycle Rules:"bucket.lifecycle.eachdo|rule|puts"#{rule.action} -#{rule.storage_class} -#{rule.age} -#{rule.matches_storage_class}"endend

REST APIs

JSON API

  1. Have gcloud CLIinstalled and initialized, which lets you generate an access token for theAuthorization header.

  2. UsecURL to call theJSON API with aGET Bucket request:

    curl-XGET\-H"Authorization: Bearer $(gcloud auth print-access-token)"\"https://storage.googleapis.com/storage/v1/b/BUCKET_NAME?fields=cors"

    WhereBUCKET_NAME is the name of thebucket whose CORS configuration you want to view. For example,my-bucket.

XML API

  1. Have gcloud CLIinstalled and initialized, which lets you generate an access token for theAuthorization header.

  2. UsecURL to call theXML API with aGET Bucket request scoped to?cors:

    curl-XGET\-H"Authorization:Bearer$(gcloudauthprint-access-token)"\"https://storage.googleapis.com/BUCKET_NAME?cors"

    WhereBUCKET_NAME is the name of thebucket whose CORS configuration you want to view. For example,my-bucket.

Remove the CORS configuration from a bucket

To remove CORS settings from a bucket, supply a CORS configuration file that'sempty.

Command line

To remove the CORS configuration from a bucket, use thegcloud storage buckets update command with the--clear-cors flag:

gcloud storage buckets update gs://BUCKET_NAME --clear-cors

ReplaceBUCKET_NAME with the name of the bucket whose CORSconfiguration you want to remove.

Client libraries

C++

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 removes any existing CORS configuration from a bucket:

namespacegcs=::google::cloud::storage;using::google::cloud::StatusOr;[](gcs::Clientclient,std::stringconst&bucket_name){StatusOr<gcs::BucketMetadata>original=client.GetBucketMetadata(bucket_name);if(!original)throwstd::move(original).status();StatusOr<gcs::BucketMetadata>patched=client.PatchBucket(bucket_name,gcs::BucketMetadataPatchBuilder().ResetCors(),gcs::IfMetagenerationMatch(original->metageneration()));if(!patched)throwstd::move(patched).status();std::cout <<"Cors configuration successfully removed for bucket "            <<patched->name() <<"\n";}

C#

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 removes any existing CORS configuration from a bucket:

usingGoogle.Apis.Storage.v1.Data;usingGoogle.Cloud.Storage.V1;usingSystem;publicclassBucketRemoveCorsConfigurationSample{publicBucketBucketRemoveCorsConfiguration(stringbucketName="your-bucket-name"){varstorage=StorageClient.Create();varbucket=storage.GetBucket(bucketName);if(bucket.Cors==null){Console.WriteLine("No CORS to remove");}else{bucket.Cors=null;bucket=storage.UpdateBucket(bucket);Console.WriteLine($"Removed CORS configuration from bucket {bucketName}.");}returnbucket;}}

Go

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 removes any existing CORS configuration from a bucket:

import("context""fmt""io""time""cloud.google.com/go/storage")// removeBucketCORSConfiguration removes the CORS configuration from a bucket.funcremoveBucketCORSConfiguration(wio.Writer,bucketNamestring)error{// bucketName := "bucket-name"ctx:=context.Background()client,err:=storage.NewClient(ctx)iferr!=nil{returnfmt.Errorf("storage.NewClient: %w",err)}deferclient.Close()ctx,cancel:=context.WithTimeout(ctx,time.Second*10)defercancel()bucket:=client.Bucket(bucketName)bucketAttrsToUpdate:=storage.BucketAttrsToUpdate{CORS:[]storage.CORS{},}if_,err:=bucket.Update(ctx,bucketAttrsToUpdate);err!=nil{returnfmt.Errorf("Bucket(%q).Update: %w",bucketName,err)}fmt.Fprintf(w,"Removed CORS configuration from a bucket %v\n",bucketName)returnnil}

Java

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 removes any existing CORS configuration from a bucket:

importcom.google.cloud.storage.Bucket;importcom.google.cloud.storage.Cors;importcom.google.cloud.storage.Storage;importcom.google.cloud.storage.StorageOptions;importjava.util.ArrayList;importjava.util.List;publicclassRemoveBucketCors{publicstaticvoidremoveBucketCors(StringprojectId,StringbucketName){// The ID of your GCP project// String projectId = "your-project-id";// The ID of your GCS bucket// String bucketName = "your-unique-bucket-name";Storagestorage=StorageOptions.newBuilder().setProjectId(projectId).build().getService();Bucketbucket=storage.get(bucketName,Storage.BucketGetOption.fields(Storage.BucketField.CORS));// getCors() returns the List and copying over to an ArrayList so it's mutable.List<Cors>cors=newArrayList<>(bucket.getCors());// Clear bucket CORS configuration.cors.clear();// Update bucket to remove CORS.bucket.toBuilder().setCors(cors).build().update();System.out.println("Removed CORS configuration from bucket "+bucketName);}}

Node.js

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 removes any existing CORS configuration from a bucket:

/** * TODO(developer): Uncomment the following lines before running the sample. */// The ID of your GCS bucket// const bucketName = 'your-unique-bucket-name';// Imports the Google Cloud client libraryconst{Storage}=require('@google-cloud/storage');// Creates a clientconststorage=newStorage();asyncfunctionremoveBucketCors(){awaitstorage.bucket(bucketName).setCorsConfiguration([]);console.log(`Removed CORS configuration from bucket${bucketName}`);}removeBucketCors().catch(console.error);

PHP

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 removes any existing CORS configuration from a bucket:

use Google\Cloud\Storage\StorageClient;/** * Remove the CORS configuration from the specified bucket. * * @param string $bucketName The name of your Cloud Storage bucket. *        (e.g. 'my-bucket') */function remove_cors_configuration(string $bucketName): void{    $storage = new StorageClient();    $bucket = $storage->bucket($bucketName);    $bucket->update([        'cors' => null,    ]);    printf('Removed CORS configuration from bucket %s', $bucketName);}

Python

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 removes any existing CORS configuration from a bucket:

fromgoogle.cloudimportstoragedefremove_cors_configuration(bucket_name):"""Remove a bucket's CORS policies configuration."""# bucket_name = "your-bucket-name"storage_client=storage.Client()bucket=storage_client.get_bucket(bucket_name)bucket.cors=[]bucket.patch()print(f"Remove CORS policies for bucket{bucket.name}.")returnbucket

Ruby

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 removes any existing CORS configuration from a bucket:

defremove_cors_configurationbucket_name:# The ID of your GCS bucket# bucket_name = "your-unique-bucket-name"require"google/cloud/storage"storage=Google::Cloud::Storage.newbucket=storage.bucketbucket_namebucket.corsdo|c|c.clearendputs"Remove CORS policies for bucket#{bucket_name}"end

REST APIs

JSON API

To remove all CORS settings from a bucket,set an empty CORSconfiguration on the bucket.

{"cors":[]}

XML API

To remove all CORS settings from a bucket,set an empty CORSconfiguration on the bucket.

<CorsConfig></CorsConfig>

What's next

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.