Contoh konfigurasi CORS

Ringkasan Penyiapan

Halaman ini menampilkan contoh konfigurasi untuk Cross-origin resource sharing (CORS). Saat menetapkan konfigurasi CORS pada bucket, Anda mengizinkan interaksi antara resource dari asal yang berbeda, sesuatu yang biasanya dilarang untuk mencegah perilaku berbahaya.

Konfigurasi CORS dasar

Misalnya Anda memiliki situs dinamis yang dapat diakses pengguna di your-example-website.appspot.com. Anda memiliki file image yang dihosting di bucket Cloud Storage bernama your-example-bucket. Anda ingin menggunakan image ini di situs Anda. Jadi, Anda harus menerapkan konfigurasi CORS di your-example-bucket yang memungkinkan browser pengguna untuk meminta resource dari bucket. Berdasarkan konfigurasi berikut, permintaan preflight valid selama 1 jam, dan permintaan browser yang berhasil akan menampilkan Content-Type resource dalam respons.

Command line

Contoh perintah gcloud

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

Contoh file JSON yang berisi konfigurasi CORS

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

Untuk mengetahui informasi lebih lanjut cara menetapkan konfigurasi CORS menggunakan Google Cloud CLI, lihat dokumentasi referensi gcloud storage buckets update.

REST API

JSON API

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

Untuk mengetahui format umum file konfigurasi CORS, lihat representasi resource bucket untuk JSON.

XML API

 <?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>
 

Untuk mengetahui format umum file konfigurasi CORS, lihat format konfigurasi CORS untuk XML.

Menghapus setelan CORS dari bucket

Untuk menghapus setelan CORS dari bucket, berikan file konfigurasi CORS yang kosong.

Command line

Saat menggunakan perintah gcloud storage buckets update dengan flag --clear-cors, Anda akan menghapus konfigurasi CORS dari bucket:

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

Dengan BUCKET_NAME adalah nama bucket yang konfigurasi CORS-nya ingin Anda hapus.

Library klien

C++

Untuk mengetahui informasi selengkapnya, lihatDokumentasi referensi Cloud Storage C++ API.

Untuk melakukan autentikasi ke Cloud Storage, siapkan Kredensial Default Aplikasi. Untuk mengetahui informasi selengkapnya, lihat Menyiapkan autentikasi untuk lingkungan pengembangan lokal.

Contoh berikut menghapus konfigurasi CORS yang ada dari 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#

Untuk mengetahui informasi selengkapnya, lihatDokumentasi referensi Cloud Storage C# API.

Untuk melakukan autentikasi ke Cloud Storage, siapkan Kredensial Default Aplikasi. Untuk mengetahui informasi selengkapnya, lihat Menyiapkan autentikasi untuk lingkungan pengembangan lokal.

Contoh berikut menghapus konfigurasi CORS yang ada dari 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

Untuk mengetahui informasi selengkapnya, lihatDokumentasi referensi Cloud Storage Go API.

Untuk melakukan autentikasi ke Cloud Storage, siapkan Kredensial Default Aplikasi. Untuk mengetahui informasi selengkapnya, lihat Menyiapkan autentikasi untuk lingkungan pengembangan lokal.

Contoh berikut menghapus konfigurasi CORS yang ada dari 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

Untuk mengetahui informasi selengkapnya, lihatDokumentasi referensi Cloud Storage Java API.

Untuk melakukan autentikasi ke Cloud Storage, siapkan Kredensial Default Aplikasi. Untuk mengetahui informasi selengkapnya, lihat Menyiapkan autentikasi untuk lingkungan pengembangan lokal.

Contoh berikut menghapus konfigurasi CORS yang ada dari 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

Untuk mengetahui informasi selengkapnya, lihatDokumentasi referensi Cloud Storage Node.js API.

Untuk melakukan autentikasi ke Cloud Storage, siapkan Kredensial Default Aplikasi. Untuk mengetahui informasi selengkapnya, lihat Menyiapkan autentikasi untuk lingkungan pengembangan lokal.

Contoh berikut menghapus konfigurasi CORS yang ada dari 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

Untuk mengetahui informasi selengkapnya, lihatDokumentasi referensi Cloud Storage PHP API.

Untuk melakukan autentikasi ke Cloud Storage, siapkan Kredensial Default Aplikasi. Untuk mengetahui informasi selengkapnya, lihat Menyiapkan autentikasi untuk lingkungan pengembangan lokal.

Contoh berikut menghapus konfigurasi CORS yang ada dari 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

Untuk mengetahui informasi selengkapnya, lihatDokumentasi referensi Cloud Storage Python API.

Untuk melakukan autentikasi ke Cloud Storage, siapkan Kredensial Default Aplikasi. Untuk mengetahui informasi selengkapnya, lihat Menyiapkan autentikasi untuk lingkungan pengembangan lokal.

Contoh berikut menghapus konfigurasi CORS yang ada dari 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

Untuk mengetahui informasi selengkapnya, lihatDokumentasi referensi Cloud Storage Ruby API.

Untuk melakukan autentikasi ke Cloud Storage, siapkan Kredensial Default Aplikasi. Untuk mengetahui informasi selengkapnya, lihat Menyiapkan autentikasi untuk lingkungan pengembangan lokal.

Contoh berikut menghapus konfigurasi CORS yang ada dari 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

REST API

JSON API

Saat ditetapkan pada bucket, konfigurasi berikut akan menghapus semua setelan CORS dari bucket:

{
  "cors": []
}

Untuk mengetahui format umum file konfigurasi CORS, lihat representasi resource bucket untuk JSON.

XML API

Saat ditetapkan pada bucket, konfigurasi berikut akan menghapus semua setelan CORS dari bucket:

<CorsConfig></CorsConfig>

Untuk mengetahui format umum file konfigurasi CORS, lihat format konfigurasi CORS untuk XML.

Langkah selanjutnya