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')