Definir e consultar as configurações do CORS

Visão geral Amostras de configuração

O compartilhamento de recursos entre origens (CORS, na sigla em inglês) permite interações entre recursos de origens diferentes, o que normalmente é proibido para evitar comportamentos maliciosos. Neste tópico, você saberá como definir uma configuração do CORS em um bucket do Cloud Storage e visualizar a configuração do CORS definida em um bucket. Consulte Exemplos de configuração do CORS.

Funções exigidas

Para receber as permissões necessárias para definir e ver a configuração do CORS em um bucket, peça ao administrador para conceder a você o papel de Administrador do Storage (roles/storage.admin) no bucket.

Esse papel predefinido contém as permissões necessárias para definir e ver as configurações do CORS. Para acessar as permissões exatas necessárias, expanda a seção Permissões necessárias:

Permissões necessárias

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

Também é possível conseguir essas permissões com outros papéis predefinidos ou personalizados.

Para informações sobre como conceder papéis nos buckets, consulte Definir e gerenciar políticas do IAM em buckets.

Definir a configuração do CORS em um bucket

Para configurar o CORS em um bucket, especifique as informações que identificam os tipos de solicitações que os buckets podem aceitar, como métodos HTTP e domínios de origem.

Siga estas etapas para definir uma configuração do CORS no bucket:

Console

  1. No console do Google Cloud , acesse a página Buckets do Cloud Storage.

    Acessar buckets

  2. Clique no nome do bucket.

  3. Clique na guia Configuração.

  4. Na seção Compartilhamento de recursos entre origens, clique em  Editar configuração do CORS.

  5. Marque a caixa de seleção Permitir compartilhamento de recursos entre origens.

  6. Clique em Adicionar uma configuração e faça o seguinte:

    1. Forneça valores para os campos na configuração:

      • Lista de origens permitidas: as origens que você quer permitir para compartilhamento de recursos entre origens com esse bucket.

      • Especificar métodos: os métodos HTTP que você quer permitir para o compartilhamento de recursos entre origens com esse bucket.

      • Lista de cabeçalhos de resposta permitidos: os cabeçalhos de resposta que você quer permitir para compartilhamento de recursos entre origens com esse bucket.

      • Tempo de expiração do cache: o número de segundos que o navegador tem permissão para fazer solicitações antes de repetir a solicitação de simulação.

      Para mais informações sobre cada campo, consulte Componentes de uma configuração do CORS.

    2. Clique em Concluído.

  7. Opcional: para adicionar outras configurações, repita a etapa anterior.

  8. Clique em Salvar.

Linha de comando

  1. Crie um arquivo JSON com a configuração do CORS que você quer aplicar. Veja exemplos de configuração para arquivos JSON de amostra.

  2. Use o comando gcloud storage buckets update com a flag --cors-file:

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

    Em que:

    • BUCKET_NAME é o nome do bucket pertinente. Por exemplo, my-bucket.
    • CORS_CONFIG_FILE é o caminho para o arquivo JSON que você criou na etapa 1.

Bibliotecas de cliente

C++

Para mais informações, consulte a documentação de referência da API Cloud Storage C++.

Para se autenticar no Cloud Storage, configure o Application Default Credentials. Saiba mais em Configurar a autenticação para bibliotecas de cliente.

Veja no exemplo a seguir como definir uma configuração CORS em um bucket:

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

  if (!original) throw std::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) throw std::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 (auto const& cors_entry : patched->cors()) {
    std::cout << "\n  " << cors_entry << "\n";
  }
}

C#

Saiba mais na documentação de referência C# da API Cloud Storage.

Para se autenticar no Cloud Storage, configure o Application Default Credentials. Saiba mais em Configurar a autenticação para bibliotecas de cliente.

Veja no exemplo a seguir como definir uma configuração CORS em um bucket:


using Google.Apis.Storage.v1.Data;
using Google.Cloud.Storage.V1;
using System;
using System.Collections.Generic;
using static Google.Apis.Storage.v1.Data.Bucket;

public class BucketAddCorsConfigurationSample
{
    public Bucket BucketAddCorsConfiguration(string bucketName = "your-bucket-name")
    {
        var storage = StorageClient.Create();
        var bucket = storage.GetBucket(bucketName);

        CorsData corsData = new CorsData
        {
            Origin = new string[] { "*" },
            ResponseHeader = new string[] { "Content-Type", "x-goog-resumable" },
            Method = new string[] { "PUT", "POST" },
            MaxAgeSeconds = 3600 //One Hour
        };

        if (bucket.Cors == null)
        {
            bucket.Cors = new List<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.");
        return bucket;
    }
}

Go

Saiba mais na documentação de referência Go da API Cloud Storage.

Para se autenticar no Cloud Storage, configure o Application Default Credentials. Saiba mais em Configurar a autenticação para bibliotecas de cliente.

Veja no exemplo a seguir como definir uma configuração CORS em um bucket:

import (
	"context"
	"fmt"
	"io"
	"time"

	"cloud.google.com/go/storage"
)

// setBucketCORSConfiguration sets a CORS configuration on a bucket.
func setBucketCORSConfiguration(w io.Writer, bucketName string, maxAge time.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)
	if err != nil {
		return fmt.Errorf("storage.NewClient: %w", err)
	}
	defer client.Close()

	ctx, cancel := context.WithTimeout(ctx, time.Second*10)
	defer cancel()

	bucket := client.Bucket(bucketName)
	bucketAttrsToUpdate := storage.BucketAttrsToUpdate{
		CORS: []storage.CORS{
			{
				MaxAge:          maxAge,
				Methods:         methods,
				Origins:         origins,
				ResponseHeaders: responseHeaders,
			}},
	}
	if _, err := bucket.Update(ctx, bucketAttrsToUpdate); err != nil {
		return fmt.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)
	return nil
}

Java

Saiba mais na documentação de referência Java da API Cloud Storage.

Para se autenticar no Cloud Storage, configure o Application Default Credentials. Saiba mais em Configurar a autenticação para bibliotecas de cliente.

Veja no exemplo a seguir como definir uma configuração CORS em um bucket:

import com.google.cloud.storage.Bucket;
import com.google.cloud.storage.Cors;
import com.google.cloud.storage.HttpMethod;
import com.google.cloud.storage.Storage;
import com.google.cloud.storage.StorageOptions;
import com.google.common.collect.ImmutableList;

public class ConfigureBucketCors {
  public static void configureBucketCors(
      String projectId,
      String bucketName,
      String origin,
      String responseHeader,
      Integer maxAgeSeconds) {
    // 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;

    Storage storage = StorageOptions.newBuilder().setProjectId(projectId).build().getService();
    Bucket bucket = 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/HTTPMethod
    HttpMethod method = HttpMethod.GET;

    Cors cors =
        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

Saiba mais na documentação de referência Node.js da API Cloud Storage.

Para se autenticar no Cloud Storage, configure o Application Default Credentials. Saiba mais em Configurar a autenticação para bibliotecas de cliente.

Veja no exemplo a seguir como definir uma configuração CORS em um bucket:

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

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

/**
 * TODO(developer): Uncomment the following lines before running the sample.
 */
// 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';

async function configureBucketCors() {
  await storage.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

Saiba mais na documentação de referência PHP da API Cloud Storage.

Para se autenticar no Cloud Storage, configure o Application Default Credentials. Saiba mais em Configurar a autenticação para bibliotecas de cliente.

Veja no exemplo a seguir como definir uma configuração CORS em um 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

Saiba mais na documentação de referência Python da API Cloud Storage.

Para se autenticar no Cloud Storage, configure o Application Default Credentials. Saiba mais em Configurar a autenticação para bibliotecas de cliente.

Veja no exemplo a seguir como definir uma configuração CORS em um bucket:

from google.cloud import storage


def cors_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}")
    return bucket

Ruby

Saiba mais na documentação de referência Ruby da API Cloud Storage.

Para se autenticar no Cloud Storage, configure o Application Default Credentials. Saiba mais em Configurar a autenticação para bibliotecas de cliente.

Veja no exemplo a seguir como definir uma configuração CORS em um bucket:

def cors_configuration bucket_name:
  # The ID of your GCS bucket
  # bucket_name = "your-unique-bucket-name"

  require "google/cloud/storage"

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

  bucket.cors do |c|
    c.add_rule ["*"],
               ["PUT", "POST"],
               headers: [
                 "Content-Type",
                 "x-goog-resumable"
               ],
               max_age: 3600
  end

  puts "Set CORS policies for bucket #{bucket_name}"
end

Rust

Veja no exemplo a seguir como definir uma configuração CORS em um bucket:

use google_cloud_storage::client::StorageControl;
use google_cloud_storage::model::bucket::Cors;
use google_cloud_wkt::FieldMask;

pub async fn sample(client: &StorageControl, bucket_id: &str) -> anyhow::Result<()> {
    let bucket = client
        .get_bucket()
        .set_name(format!("projects/_/buckets/{bucket_id}"))
        .send()
        .await?;
    let metageneration = bucket.metageneration;
    let mut cors = bucket.cors.clone();
    cors.push(
        Cors::new()
            .set_origin(["http://example.appspot.com".to_string()])
            .set_method(["GET".to_string(), "HEAD".to_string(), "DELETE".to_string()])
            .set_response_header(["Content-Type".to_string()])
            .set_max_age_seconds(3600),
    );

    let bucket = client
        .update_bucket()
        .set_bucket(bucket.set_cors(cors))
        .set_if_metageneration_match(metageneration)
        .set_update_mask(FieldMask::default().set_paths(["cors"]))
        .send()
        .await?;
    println!("successfully updated bucket CORS for {bucket_id}: {bucket:?}");
    Ok(())
}

APIs REST

API JSON

  1. Ter a CLI gcloud instalada e inicializada, o que permite gerar um token de acesso para o cabeçalho Authorization.

  2. Crie um arquivo JSON com a configuração do CORS que você quer aplicar. Confira exemplos de configuração para arquivos JSON de amostra.

  3. Use cURL para chamar a API JSON com uma solicitação bucket PATCH:

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

    Em que:

    • BUCKET_NAME é o nome do bucket. Por exemplo, my-bucket.
    • CORS_CONFIG_FILE é o caminho para o arquivo JSON que você criou na etapa 2.

API XML

  1. Ter a CLI gcloud instalada e inicializada, o que permite gerar um token de acesso para o cabeçalho Authorization.

  2. Crie um arquivo XML com a configuração do CORS que você quer aplicar. Confira exemplos de arquivos XML nos exemplos de configuração.

  3. Use cURL para chamar a API XML com uma solicitação PUT Bucket com escopo ?cors:

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

    Em que:

    • BUCKET_NAME é o nome do bucket. Por exemplo, my-bucket.
    • PROJECT_ID é o ID do projeto associado ao bucket. Por exemplo, my-project.
    • CORS_CONFIG_FILE é o caminho para o arquivo XML criado na Etapa 2.

Visualizar a configuração do CORS para um bucket

Console

  1. No console do Google Cloud , acesse a página Buckets do Cloud Storage.

    Acessar buckets

  2. Clique no nome do bucket.

  3. Clique na guia Configuração.

  4. Na seção Compartilhamento de recursos entre origens, clique em  Editar configuração do CORS.

  5. Clique na configuração.

  6. Opcional: edite a configuração ou clique em Cancelar para fechar a caixa de diálogo.

Linha de comando

Use o comando gcloud storage buckets describe com a flag --format:

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

Em que BUCKET_NAME é o nome do bucket com a configuração de CORS que você quer visualizar. Por exemplo, my-bucket.

Bibliotecas de cliente

Para ver a configuração do CORS para um bucket usando as bibliotecas de cliente, siga as instruções para exibir os metadados de um bucket e procure o campo CORS na resposta.

C++

Para mais informações, consulte a documentação de referência da API Cloud Storage C++.

Para se autenticar no Cloud Storage, configure o Application Default Credentials. Saiba mais em Configurar a autenticação para bibliotecas de cliente.

namespace gcs = ::google::cloud::storage;
using ::google::cloud::StatusOr;
[](gcs::Client client, std::string const& bucket_name) {
  StatusOr<gcs::BucketMetadata> bucket_metadata =
      client.GetBucketMetadata(bucket_name);
  if (!bucket_metadata) throw std::move(bucket_metadata).status();

  std::cout << "The metadata for bucket " << bucket_metadata->name() << " is "
            << *bucket_metadata << "\n";
}

C#

Saiba mais na documentação de referência C# da API Cloud Storage.

Para se autenticar no Cloud Storage, configure o Application Default Credentials. Saiba mais em Configurar a autenticação para bibliotecas de cliente.


using Google.Apis.Storage.v1.Data;
using Google.Cloud.Storage.V1;
using System;

public class GetBucketMetadataSample
{
    public Bucket GetBucketMetadata(string bucketName = "your-unique-bucket-name")
    {
        var storage = StorageClient.Create();
        var bucket = storage.GetBucket(bucketName, new GetBucketOptions { 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 (var label in bucket.Labels)
            {
                Console.WriteLine($"{label.Key}:\t{label.Value}");
            }
        }
        return bucket;
    }
}

Go

Saiba mais na documentação de referência Go da API Cloud Storage.

Para se autenticar no Cloud Storage, configure o Application Default Credentials. Saiba mais em Configurar a autenticação para bibliotecas de cliente.

import (
	"context"
	"fmt"
	"io"
	"time"

	"cloud.google.com/go/storage"
)

// getBucketMetadata gets the bucket metadata.
func getBucketMetadata(w io.Writer, bucketName string) (*storage.BucketAttrs, error) {
	// bucketName := "bucket-name"
	ctx := context.Background()
	client, err := storage.NewClient(ctx)
	if err != nil {
		return nil, fmt.Errorf("storage.NewClient: %w", err)
	}
	defer client.Close()

	ctx, cancel := context.WithTimeout(ctx, time.Second*10)
	defer cancel()
	attrs, err := client.Bucket(bucketName).Attrs(ctx)
	if err != nil {
		return nil, 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)
	if attrs.Encryption != nil {
		fmt.Fprintf(w, "DefaultKmsKeyName: %v\n", attrs.Encryption.DefaultKMSKeyName)
	}
	if attrs.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)
	if attrs.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)
	if attrs.Logging != nil {
		fmt.Fprintf(w, "LogBucket: %v\n", attrs.Logging.LogBucket)
		fmt.Fprintf(w, "LogObjectPrefix: %v\n", attrs.Logging.LogObjectPrefix)
	}
	if attrs.CORS != nil {
		fmt.Fprintln(w, "CORS:")
		for _, v := range attrs.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)
		}
	}
	if attrs.Labels != nil {
		fmt.Fprintf(w, "\n\n\nLabels:")
		for key, value := range attrs.Labels {
			fmt.Fprintf(w, "\t%v = %v\n", key, value)
		}
	}
	return attrs, nil
}

Java

Saiba mais na documentação de referência Java da API Cloud Storage.

Para se autenticar no Cloud Storage, configure o Application Default Credentials. Saiba mais em Configurar a autenticação para bibliotecas de cliente.


import com.google.cloud.storage.Bucket;
import com.google.cloud.storage.BucketInfo;
import com.google.cloud.storage.Storage;
import com.google.cloud.storage.StorageOptions;
import java.util.Map;

public class GetBucketMetadata {
  public static void getBucketMetadata(String projectId, String bucketName) {
    // The ID of your GCP project
    // String projectId = "your-project-id";

    // The ID of your GCS bucket
    // String bucketName = "your-unique-bucket-name";

    Storage storage = StorageOptions.newBuilder().setProjectId(projectId).build().getService();

    // Select all fields. Fields can be selected individually e.g. Storage.BucketField.NAME
    Bucket bucket =
        storage.get(bucketName, Storage.BucketGetOption.fields(Storage.BucketField.values()));

    // Print bucket metadata
    System.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.LifecycleRule rule : bucket.getLifecycleRules()) {
        System.out.println(rule);
      }
    }
  }
}

Node.js

Saiba mais na documentação de referência Node.js da API Cloud Storage.

Para se autenticar no Cloud Storage, configure o Application Default Credentials. Saiba mais em Configurar a autenticação para bibliotecas de cliente.

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

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

async function getBucketMetadata() {
  /**
   * TODO(developer): Uncomment the following lines before running the sample.
   */
  // The ID of your GCS bucket
  // const bucketName = 'your-unique-bucket-name';

  // Get Bucket Metadata
  const [metadata] = await storage.bucket(bucketName).getMetadata();

  console.log(JSON.stringify(metadata, null, 2));
}

PHP

Saiba mais na documentação de referência PHP da API Cloud Storage.

Para se autenticar no Cloud Storage, configure o Application Default Credentials. Saiba mais em Configurar a autenticação para bibliotecas de cliente.

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

Saiba mais na documentação de referência Python da API Cloud Storage.

Para se autenticar no Cloud Storage, configure o Application Default Credentials. Saiba mais em Configurar a autenticação para bibliotecas de cliente.


from google.cloud import storage


def bucket_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

Saiba mais na documentação de referência Ruby da API Cloud Storage.

Para se autenticar no Cloud Storage, configure o Application Default Credentials. Saiba mais em Configurar a autenticação para bibliotecas de cliente.

def get_bucket_metadata bucket_name:
  # The ID of your GCS bucket
  # bucket_name = "your-unique-bucket-name"

  require "google/cloud/storage"

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

  puts "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.each do |key, value|
    puts " - #{key} = #{value}"
  end
  puts "Lifecycle Rules:"
  bucket.lifecycle.each do |rule|
    puts "#{rule.action} - #{rule.storage_class} - #{rule.age} - #{rule.matches_storage_class}"
  end
end

Rust

use google_cloud_storage::client::StorageControl;

pub async fn sample(client: &StorageControl, bucket_id: &str) -> anyhow::Result<()> {
    let bucket = client
        .get_bucket()
        .set_name(format!("projects/_/buckets/{bucket_id}"))
        .send()
        .await?;
    println!("successfully obtained bucket metadata {bucket:?}");
    Ok(())
}

APIs REST

API JSON

  1. Ter a CLI gcloud instalada e inicializada, o que permite gerar um token de acesso para o cabeçalho Authorization.

  2. Use cURL para chamar a API JSON com uma solicitação de bucket GET:

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

    Em que BUCKET_NAME é o nome do bucket com a configuração do CORS que você quer ver. Por exemplo, my-bucket.

API XML

  1. Ter a CLI gcloud instalada e inicializada, o que permite gerar um token de acesso para o cabeçalho Authorization.

  2. Use cURL para chamar a API XML com uma solicitação do bucket GET com o escopo definido como ?cors:

    curl -X GET \
      -H "Authorization: Bearer $(gcloud auth print-access-token)" \
      "https://storage.googleapis.com/BUCKET_NAME?cors"

    Em que BUCKET_NAME é o nome do bucket com a configuração do CORS que você quer ver. Por exemplo, my-bucket.

Remover a configuração do CORS de um bucket

Console

  1. No console do Google Cloud , acesse a página Buckets do Cloud Storage.

    Acessar buckets

  2. Clique no nome do bucket.

  3. Clique na guia Configuração.

  4. Na seção Compartilhamento de recursos entre origens, clique em  Editar configuração do CORS.

  5. Faça uma das seguintes ações:

    • Para excluir uma configuração específica do CORS, clique em  Excluir na configuração que você quer remover.

    • Para desativar o CORS e excluir todas as configurações do CORS do bucket, desmarque a caixa de seleção Permitir compartilhamento de recursos entre origens.

  6. Clique em Salvar.

Linha de comando

Para remover a configuração do CORS de um bucket, use o comando gcloud storage buckets update com a flag --clear-cors:

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

Substitua BUCKET_NAME pelo nome do bucket com a configuração de CORS que você quer remover.

Bibliotecas de cliente

C++

Para mais informações, consulte a documentação de referência da API Cloud Storage C++.

Para se autenticar no Cloud Storage, configure o Application Default Credentials. Saiba mais em Configurar a autenticação para bibliotecas de cliente.

O exemplo a seguir remove qualquer configuração CORS de um bucket:

namespace gcs = ::google::cloud::storage;
using ::google::cloud::StatusOr;
[](gcs::Client client, std::string const& bucket_name) {
  StatusOr<gcs::BucketMetadata> original =
      client.GetBucketMetadata(bucket_name);
  if (!original) throw std::move(original).status();

  StatusOr<gcs::BucketMetadata> patched = client.PatchBucket(
      bucket_name, gcs::BucketMetadataPatchBuilder().ResetCors(),
      gcs::IfMetagenerationMatch(original->metageneration()));
  if (!patched) throw std::move(patched).status();

  std::cout << "Cors configuration successfully removed for bucket "
            << patched->name() << "\n";
}

C#

Saiba mais na documentação de referência C# da API Cloud Storage.

Para se autenticar no Cloud Storage, configure o Application Default Credentials. Saiba mais em Configurar a autenticação para bibliotecas de cliente.

O exemplo a seguir remove qualquer configuração CORS de um bucket:


using Google.Apis.Storage.v1.Data;
using Google.Cloud.Storage.V1;
using System;

public class BucketRemoveCorsConfigurationSample
{
	public Bucket BucketRemoveCorsConfiguration(string bucketName = "your-bucket-name")
	{
        var storage = StorageClient.Create();
        var bucket = 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}.");
        }

        return bucket;
	}
}

Go

Saiba mais na documentação de referência Go da API Cloud Storage.

Para se autenticar no Cloud Storage, configure o Application Default Credentials. Saiba mais em Configurar a autenticação para bibliotecas de cliente.

O exemplo a seguir remove qualquer configuração CORS de um bucket:

import (
	"context"
	"fmt"
	"io"
	"time"

	"cloud.google.com/go/storage"
)

// removeBucketCORSConfiguration removes the CORS configuration from a bucket.
func removeBucketCORSConfiguration(w io.Writer, bucketName string) error {
	// bucketName := "bucket-name"
	ctx := context.Background()
	client, err := storage.NewClient(ctx)
	if err != nil {
		return fmt.Errorf("storage.NewClient: %w", err)
	}
	defer client.Close()

	ctx, cancel := context.WithTimeout(ctx, time.Second*10)
	defer cancel()

	bucket := client.Bucket(bucketName)
	bucketAttrsToUpdate := storage.BucketAttrsToUpdate{
		CORS: []storage.CORS{},
	}
	if _, err := bucket.Update(ctx, bucketAttrsToUpdate); err != nil {
		return fmt.Errorf("Bucket(%q).Update: %w", bucketName, err)
	}
	fmt.Fprintf(w, "Removed CORS configuration from a bucket %v\n", bucketName)
	return nil
}

Java

Saiba mais na documentação de referência Java da API Cloud Storage.

Para se autenticar no Cloud Storage, configure o Application Default Credentials. Saiba mais em Configurar a autenticação para bibliotecas de cliente.

O exemplo a seguir remove qualquer configuração CORS de um bucket:


import com.google.cloud.storage.Bucket;
import com.google.cloud.storage.Cors;
import com.google.cloud.storage.Storage;
import com.google.cloud.storage.StorageOptions;
import java.util.ArrayList;
import java.util.List;

public class RemoveBucketCors {
  public static void removeBucketCors(String projectId, String bucketName) {
    // The ID of your GCP project
    // String projectId = "your-project-id";

    // The ID of your GCS bucket
    // String bucketName = "your-unique-bucket-name";

    Storage storage = StorageOptions.newBuilder().setProjectId(projectId).build().getService();
    Bucket bucket =
        storage.get(bucketName, Storage.BucketGetOption.fields(Storage.BucketField.CORS));

    // getCors() returns the List and copying over to an ArrayList so it's mutable.
    List<Cors> cors = new ArrayList<>(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

Saiba mais na documentação de referência Node.js da API Cloud Storage.

Para se autenticar no Cloud Storage, configure o Application Default Credentials. Saiba mais em Configurar a autenticação para bibliotecas de cliente.

O exemplo a seguir remove qualquer configuração CORS de um 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 library
const {Storage} = require('@google-cloud/storage');

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

async function removeBucketCors() {
  await storage.bucket(bucketName).setCorsConfiguration([]);

  console.log(`Removed CORS configuration from bucket ${bucketName}`);
}

removeBucketCors().catch(console.error);

PHP

Saiba mais na documentação de referência PHP da API Cloud Storage.

Para se autenticar no Cloud Storage, configure o Application Default Credentials. Saiba mais em Configurar a autenticação para bibliotecas de cliente.

O exemplo a seguir remove qualquer configuração CORS de um 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

Saiba mais na documentação de referência Python da API Cloud Storage.

Para se autenticar no Cloud Storage, configure o Application Default Credentials. Saiba mais em Configurar a autenticação para bibliotecas de cliente.

O exemplo a seguir remove qualquer configuração CORS de um bucket:

from google.cloud import storage


def remove_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}.")
    return bucket

Ruby

Saiba mais na documentação de referência Ruby da API Cloud Storage.

Para se autenticar no Cloud Storage, configure o Application Default Credentials. Saiba mais em Configurar a autenticação para bibliotecas de cliente.

O exemplo a seguir remove qualquer configuração CORS de um bucket:

def remove_cors_configuration bucket_name:
  # The ID of your GCS bucket
  # bucket_name = "your-unique-bucket-name"

  require "google/cloud/storage"

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

  bucket.cors do |c|
    c.clear
  end

  puts "Remove CORS policies for bucket #{bucket_name}"
end

Rust

O exemplo a seguir remove qualquer configuração CORS de um bucket:

use google_cloud_storage::client::StorageControl;
use google_cloud_storage::model::bucket::Cors;
use google_cloud_wkt::FieldMask;

pub async fn sample(client: &StorageControl, bucket_id: &str) -> anyhow::Result<()> {
    let bucket = client
        .get_bucket()
        .set_name(format!("projects/_/buckets/{bucket_id}"))
        .send()
        .await?;
    let metageneration = bucket.metageneration;

    let bucket = client
        .update_bucket()
        .set_bucket(bucket.set_cors(Vec::<Cors>::new()))
        .set_if_metageneration_match(metageneration)
        .set_update_mask(FieldMask::default().set_paths(["cors"]))
        .send()
        .await?;
    println!(
        "successfully removed CORS rule for bucket {bucket_id}: {:?}",
        bucket.cors
    );
    Ok(())
}

APIs REST

API JSON

Para remover todas as configurações de CORS de um bucket, defina uma configuração de CORS vazia no bucket.

{
  "cors": []
}

API XML

Para remover todas as configurações de CORS de um bucket, defina uma configuração de CORS vazia no bucket.

<CorsConfig></CorsConfig>

A seguir