Esempi di configurazione CORS

Panoramica Configurazione

Questa pagina mostra configurazioni di esempio per Condivisione delle risorse tra origini (CORS). Quando imposti una configurazione CORS su un bucket, consenti le interazioni tra risorse di origini diverse, cosa che in genere è vietato al fine di evitare comportamenti dannosi.

Configurazione CORS di base

Supponiamo che tu abbia un sito web dinamico che gli utenti possono accedi all'indirizzo your-example-website.appspot.com. Hai un file immagine ospitato in Bucket Cloud Storage denominato your-example-bucket. Vorresti utilizzare sull'immagine sul tuo sito web, quindi devi applicare una configurazione CORS your-example-bucket che consente ai tuoi utenti per richiedere risorse dal bucket. In base alla configurazione seguente, le richieste preflight vengono valide per 1 ora e le richieste del browser andate a buon fine restituiscono il Content-Type di la risorsa nella risposta.

Riga di comando

Esempio di comando gcloud

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

Esempio di file JSON contenente la configurazione CORS

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

Per ulteriori informazioni su come impostare una configurazione CORS utilizzando Google Cloud CLI, consulta documentazione di riferimento di gcloud storage buckets update.

API REST

API JSON

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

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

API XML

 <?xml version="1.0" encoding="UTF-8"?>
 <CorsConfig>
   <Cors>
     <Origins>
       <Origin>https://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 che sia vuoto.

Riga di comando

Quando utilizzi il comando gcloud storage buckets update con --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 la cui configurazione CORS che vuoi rimuovere.

Librerie client

C++

Per ulteriori informazioni, consulta API Cloud Storage C++ documentazione di riferimento.

Per eseguire l'autenticazione su Cloud Storage, configura Credenziali predefinite dell'applicazione. Per ulteriori informazioni, vedi Configura 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 ulteriori informazioni, consulta API Cloud Storage C# documentazione di riferimento.

Per eseguire l'autenticazione su Cloud Storage, configura Credenziali predefinite dell'applicazione. Per ulteriori informazioni, vedi Configura 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 ulteriori informazioni, consulta API Cloud Storage Go documentazione di riferimento.

Per eseguire l'autenticazione su Cloud Storage, configura Credenziali predefinite dell'applicazione. Per ulteriori informazioni, vedi Configura 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.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

Per ulteriori informazioni, consulta API Cloud Storage Java documentazione di riferimento.

Per eseguire l'autenticazione su Cloud Storage, configura Credenziali predefinite dell'applicazione. Per ulteriori informazioni, vedi Configura 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 ulteriori informazioni, consulta API Cloud Storage Node.js documentazione di riferimento.

Per eseguire l'autenticazione su Cloud Storage, configura Credenziali predefinite dell'applicazione. Per ulteriori informazioni, vedi Configura 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 ulteriori informazioni, consulta API Cloud Storage PHP documentazione di riferimento.

Per eseguire l'autenticazione su Cloud Storage, configura Credenziali predefinite dell'applicazione. Per ulteriori informazioni, vedi Configura 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 ulteriori informazioni, consulta API Cloud Storage Python documentazione di riferimento.

Per eseguire l'autenticazione su Cloud Storage, configura Credenziali predefinite dell'applicazione. Per ulteriori informazioni, vedi Configura 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 ulteriori informazioni, consulta API Cloud Storage Ruby documentazione di riferimento.

Per eseguire l'autenticazione su Cloud Storage, configura Credenziali predefinite dell'applicazione. Per ulteriori informazioni, vedi Configura 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

Quando è impostata su un bucket, la seguente configurazione rimuove tutti Impostazioni CORS da un bucket:

{
  "cors": []
}

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

API XML

Quando è impostata su un bucket, la seguente configurazione rimuove tutti 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