CORS 構成の例

概要 設定

このページでは、クロスオリジン リソース シェアリング(CORS)の構成例について説明します。バケットに CORS 構成を設定すると、異なるオリジンのリソース間のインタラクションを許可できます。これは通常、悪意のある動作を防ぐために禁止されています。

基本的な CORS 構成

ユーザーが your-example-website.appspot.com でアクセスできる動的ウェブサイトがあるとします。your-example-bucket という名前の Cloud Storage バケットに画像ファイルがホストされています。ウェブサイトで画像を使用するには、your-example-bucket に CORS 構成を適用して、ユーザーのブラウザがバケットからリソースをリクエストできるようにする必要があります。以下の構成に基づいているため、プリフライト リクエストは 1 時間有効であり、ブラウザ リクエストが成功するとレスポンスでリソースの Content-Type が返されます。

コマンドライン

gcloud コマンドの例

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

CORS 構成を含む JSON ファイルの例

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

Google Cloud CLI を使用して CORS 構成を設定する方法の詳細については、gcloud storage buckets update リファレンス ドキュメントをご覧ください。

REST API

JSON API

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

CORS 構成ファイルの一般的な形式については、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>
 

CORS 構成ファイルの一般的な形式については、XML の CORS 構成形式をご覧ください。

バケットから CORS 設定を削除する

バケットから CORS 設定を削除するには、空の CORS 構成ファイルを指定します。

コマンドライン

--clear-cors フラグを指定して gcloud storage buckets update コマンドを使用する場合は、バケットから CORS 構成を削除します。

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

ここで、BUCKET_NAME は、CORS 構成を削除するバケットの名前です。

クライアント ライブラリ

C++

詳細については、Cloud Storage C++ API のリファレンス ドキュメントをご覧ください。

Cloud Storage に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証を設定するをご覧ください。

次のサンプルでは、既存の CORS 構成をバケットから削除します。

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#

詳細については、Cloud Storage C# API のリファレンス ドキュメントをご覧ください。

Cloud Storage に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証を設定するをご覧ください。

次のサンプルでは、既存の CORS 構成をバケットから削除します。


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

詳細については、Cloud Storage Go API のリファレンス ドキュメントをご覧ください。

Cloud Storage に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証を設定するをご覧ください。

次のサンプルでは、既存の CORS 構成をバケットから削除します。

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

詳細については、Cloud Storage Java API のリファレンス ドキュメントをご覧ください。

Cloud Storage に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証を設定するをご覧ください。

次のサンプルでは、既存の CORS 構成をバケットから削除します。


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

詳細については、Cloud Storage Node.js API のリファレンス ドキュメントをご覧ください。

Cloud Storage に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証を設定するをご覧ください。

次のサンプルでは、既存の CORS 構成をバケットから削除します。

/**
 * 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

詳細については、Cloud Storage PHP API のリファレンス ドキュメントをご覧ください。

Cloud Storage に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証を設定するをご覧ください。

次のサンプルでは、既存の CORS 構成をバケットから削除します。

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

詳細については、Cloud Storage Python API のリファレンス ドキュメントをご覧ください。

Cloud Storage に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証を設定するをご覧ください。

次のサンプルでは、既存の CORS 構成をバケットから削除します。

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

詳細については、Cloud Storage Ruby API のリファレンス ドキュメントをご覧ください。

Cloud Storage に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証を設定するをご覧ください。

次のサンプルでは、既存の CORS 構成をバケットから削除します。

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

バケットに設定すると、次の構成ではバケットからすべての CORS 設定が削除されます。

{
  "cors": []
}

CORS 構成ファイルの一般的な形式については、JSON のバケット リソース表現をご覧ください。

XML API

バケットに設定すると、次の構成ではバケットからすべての CORS 設定が削除されます。

<CorsConfig></CorsConfig>

CORS 構成ファイルの一般的な形式については、XML の CORS 構成形式をご覧ください。

次のステップ