Esempi di configurazione CORS

Panoramica Configurazione

Questa pagina mostra configurazioni di esempio per la condivisione delle risorse tra origini (CORS). Quando imposti una configurazione CORS su un bucket, consenti le interazioni tra risorse di origini diverse, attività che in genere è vietata per evitare comportamenti dannosi.

Configurazione CORS di base

Supponiamo che tu abbia un sito web dinamico a cui gli utenti possono accedere da your-example-website.appspot.com. Hai un file immagine ospitato in un bucket Cloud Storage denominato your-example-bucket. Vuoi utilizzare l'immagine sul tuo sito web, quindi devi applicare una configurazione CORS a your-example-bucket che consenta ai browser degli utenti di richiedere risorse dal bucket. In base alla seguente configurazione, le richieste preflight valide per un'ora e le richieste del browser andate a buon fine restituiscono il valore Content-Type della risorsa nella risposta.

Riga di comando

Comando gcloud di esempio

gcloud storage buckets update gs://example_bucket --cors-file=example_cors_file.json

File JSON di esempio contenente la configurazione CORS

[
    {
      "origin": ["http://your-example-website.appspot.com"],
      "method": ["GET"],
      "responseHeader": ["Content-Type"],
      "maxAgeSeconds": 3600
    }
]

Per saperne di più su come impostare una configurazione CORS utilizzando Google Cloud CLI, consulta la documentazione di riferimento di gcloud storage buckets update.

API REST

API JSON

{
  "cors": [
    {
      "origin": ["http://your-example-website.appspot.com"],
      "method": ["GET"],
      "responseHeader": ["Content-Type"],
      "maxAgeSeconds": 3600
    }
  ]
}

Per il formato generalizzato di un file di configurazione CORS, consulta la rappresentazione delle risorse dei bucket per JSON.

API XML

 <?xml version="1.0" encoding="UTF-8"?>
 <CorsConfig>
   <Cors>
     <Origins>
       <Origin>http://your-example-website.appspot.com</Origin>
     </Origins>
     <Methods>
       <Method>GET</Method>
     </Methods>
     <ResponseHeaders>
       <ResponseHeader>Content-Type</ResponseHeader>
     </ResponseHeaders>
     <MaxAgeSec>3600</MaxAgeSec>
   </Cors>
 </CorsConfig>
 

Per il formato generalizzato di un file di configurazione CORS, consulta Formato di configurazione CORS per XML.

Rimuovi le impostazioni CORS da un bucket

Per rimuovere le impostazioni CORS da un bucket, fornisci un file di configurazione CORS vuoto.

Riga di comando

Quando utilizzi il comando gcloud storage buckets update con il flag --clear-cors, rimuovi la configurazione CORS da un bucket:

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

Dove BUCKET_NAME è il nome del bucket di cui vuoi rimuovere la configurazione CORS.

Librerie client

C++

Per maggiori informazioni, consulta la documentazione di riferimento dell'API C++ di Cloud Storage.

Per eseguire l'autenticazione in Cloud Storage, configura Credenziali predefinite dell'applicazione. Per maggiori informazioni, consulta Configurare l'autenticazione per un ambiente di sviluppo locale.

L'esempio seguente rimuove qualsiasi configurazione CORS esistente da un 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#

Per maggiori informazioni, consulta la documentazione di riferimento dell'API C# di Cloud Storage.

Per eseguire l'autenticazione in Cloud Storage, configura Credenziali predefinite dell'applicazione. Per maggiori informazioni, consulta Configurare l'autenticazione per un ambiente di sviluppo locale.

L'esempio seguente rimuove qualsiasi configurazione CORS esistente da un 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

Per maggiori informazioni, consulta la documentazione di riferimento dell'API Go di Cloud Storage.

Per eseguire l'autenticazione in Cloud Storage, configura Credenziali predefinite dell'applicazione. Per maggiori informazioni, consulta Configurare l'autenticazione per un ambiente di sviluppo locale.

L'esempio seguente rimuove qualsiasi configurazione CORS esistente da un bucket:

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

	"cloud.go888ogle.com.fqhub.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

Per maggiori informazioni, consulta la documentazione di riferimento dell'API Java di Cloud Storage.

Per eseguire l'autenticazione in Cloud Storage, configura Credenziali predefinite dell'applicazione. Per maggiori informazioni, consulta Configurare l'autenticazione per un ambiente di sviluppo locale.

L'esempio seguente rimuove qualsiasi configurazione CORS esistente da un 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

Per maggiori informazioni, consulta la documentazione di riferimento dell'API Node.js di Cloud Storage.

Per eseguire l'autenticazione in Cloud Storage, configura Credenziali predefinite dell'applicazione. Per maggiori informazioni, consulta Configurare l'autenticazione per un ambiente di sviluppo locale.

L'esempio seguente rimuove qualsiasi configurazione CORS esistente da un 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

Per maggiori informazioni, consulta la documentazione di riferimento dell'API PHP di Cloud Storage.

Per eseguire l'autenticazione in Cloud Storage, configura Credenziali predefinite dell'applicazione. Per maggiori informazioni, consulta Configurare l'autenticazione per un ambiente di sviluppo locale.

L'esempio seguente rimuove qualsiasi configurazione CORS esistente da un 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

Per maggiori informazioni, consulta la documentazione di riferimento dell'API Python di Cloud Storage.

Per eseguire l'autenticazione in Cloud Storage, configura Credenziali predefinite dell'applicazione. Per maggiori informazioni, consulta Configurare l'autenticazione per un ambiente di sviluppo locale.

L'esempio seguente rimuove qualsiasi configurazione CORS esistente da un 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

Per maggiori informazioni, consulta la documentazione di riferimento dell'API Ruby di Cloud Storage.

Per eseguire l'autenticazione in Cloud Storage, configura Credenziali predefinite dell'applicazione. Per maggiori informazioni, consulta Configurare l'autenticazione per un ambiente di sviluppo locale.

L'esempio seguente rimuove qualsiasi configurazione CORS esistente da un 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

API REST

API JSON

Se impostata su un bucket, la configurazione seguente rimuove tutte le impostazioni CORS da un bucket:

{
  "cors": []
}

Per il formato generalizzato di un file di configurazione CORS, consulta la rappresentazione delle risorse dei bucket per JSON.

API XML

Se impostata su un bucket, la configurazione seguente rimuove tutte le impostazioni CORS da un bucket:

<CorsConfig></CorsConfig>

Per il formato generalizzato di un file di configurazione CORS, consulta Formato di configurazione CORS per XML.

Passaggi successivi