CORS 구성 설정 및 보기

개요 구성 샘플

교차 출처 리소스 공유(CORS)는 출처가 다른 리소스 간의 상호작용을 허용합니다. 일반적으로 이러한 상호작용은 악의적인 행동을 방지하기 위해 금지되어 있습니다. 이 페이지를 통해 Cloud Storage 버킷에서 CORS 구성을 설정하는 방법과 버킷에서 설정된 CORS 구성을 보는 방법을 알아봅니다. 버킷의 기존 구성을 사용 중지하는 구성을 비롯한 CORS 구성 예시는 CORS 구성 예시를 참조하세요.

버킷의 CORS 구성 설정

버킷이 수락할 수 있는 요청 유형을 식별하는 HTTP 메서드 및 출처 도메인과 같은 정보를 지정하여 버킷에 CORS 구성을 설정합니다.

버킷에 CORS 구성을 설정하려면 다음 단계를 따르세요.

콘솔

Google Cloud 콘솔을 사용하여 CORS를 관리할 수 없습니다. 대신 gcloud CLI를 사용하세요.

명령줄

  1. 적용하려는 CORS 구성을 사용해서 JSON 파일을 만듭니다. 샘플 JSON 파일은 구성 예시를 참조하세요.

  2. gcloud storage buckets update 명령어를 --cors-file 플래그와 함께 사용합니다.

    gcloud storage buckets update gs://BUCKET_NAME --cors-file=CORS_CONFIG_FILE

    각 항목의 의미는 다음과 같습니다.

    • BUCKET_NAME은 관련 버킷의 이름입니다. 예를 들면 my-bucket입니다.
    • CORS_CONFIG_FILE은 1단계에서 만든 JSON 파일의 경로입니다.

클라이언트 라이브러리

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,
   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#

자세한 내용은 Cloud Storage C# API 참조 문서를 확인하세요.

Cloud Storage에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

다음 샘플에서는 버킷에 CORS 구성을 설정합니다.


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

자세한 내용은 Cloud Storage Go API 참조 문서를 확인하세요.

Cloud Storage에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

다음 샘플에서는 버킷에 CORS 구성을 설정합니다.

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

자세한 내용은 Cloud Storage Java API 참조 문서를 확인하세요.

Cloud Storage에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

다음 샘플에서는 버킷에 CORS 구성을 설정합니다.

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

자세한 내용은 Cloud Storage Node.js API 참조 문서를 확인하세요.

Cloud Storage에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

다음 샘플에서는 버킷에 CORS 구성을 설정합니다.

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

자세한 내용은 Cloud Storage PHP API 참조 문서를 확인하세요.

Cloud Storage에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

다음 샘플에서는 버킷에 CORS 구성을 설정합니다.

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')
 * @param string $responseHeader The response header to share across origins.
 *        (e.g. 'Content-Type')
 * @param int $maxAgeSeconds The maximum amount of time the browser can make
 *        (e.g. 3600)
 *     requests before it must repeat preflighted requests.
 */
function cors_configuration(string $bucketName, string $method, string $origin, string $responseHeader, int $maxAgeSeconds): void
{
    $storage = new StorageClient();
    $bucket = $storage->bucket($bucketName);

    $bucket->update([
        'cors' => [
            [
                'method' => [$method],
                'origin' => [$origin],
                'responseHeader' => [$responseHeader],
                'maxAgeSeconds' => $maxAgeSeconds,
            ]
        ]
    ]);

    printf(
        'Bucket %s was updated with a CORS config to allow GET requests from ' .
        '%s sharing %s responses across origins.',
        $bucketName,
        $origin,
        $responseHeader
    );
}

Python

자세한 내용은 Cloud Storage Python API 참조 문서를 확인하세요.

Cloud Storage에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

다음 샘플에서는 버킷에 CORS 구성을 설정합니다.

from google.cloud import storage


def cors_configuration(bucket_name):
    """Set a bucket's CORS policies configuration."""
    # bucket_name = "your-bucket-name"

    storage_client = storage.Client()
    bucket = storage_client.get_bucket(bucket_name)
    bucket.cors = [
        {
            "origin": ["*"],
            "responseHeader": [
                "Content-Type",
                "x-goog-resumable"],
            "method": ['PUT', 'POST'],
            "maxAgeSeconds": 3600
        }
    ]
    bucket.patch()

    print(f"Set CORS policies for bucket {bucket.name} is {bucket.cors}")
    return bucket

Ruby

자세한 내용은 Cloud Storage Ruby API 참조 문서를 확인하세요.

Cloud Storage에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

다음 샘플에서는 버킷에 CORS 구성을 설정합니다.

def 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.add_rule ["*"],
               ["PUT", "POST"],
               headers: [
                 "Content-Type",
                 "x-goog-resumable"
               ],
               max_age: 3600
  end

  puts "Set CORS policies for bucket #{bucket_name}"
end

REST API

JSON API

  1. Authorization 헤더에 대한 액세스 토큰을 생성하려면 gcloud CLI가 설치 및 초기화되어 있어야 합니다.

    또는 OAuth 2.0 Playground를 사용하여 액세스 토큰을 만들고 Authorization 헤더에 포함할 수 있습니다.

  2. 적용하려는 CORS 구성을 사용해서 JSON 파일을 만듭니다. 샘플 JSON 파일은 구성 예시를 참조하세요.

  3. cURL을 사용하여 PATCH 버킷 요청으로 JSON API를 호출합니다.

    curl --request PATCH \
     'https://storage.googleapis.com/storage/v1/b/BUCKET_NAME?fields=cors' \
     --header 'Authorization: Bearer $(gcloud auth print-access-token)' \
     --header 'Content-Type: application/json' \
     --data-binary @CORS_CONFIG_FILE

    각 항목의 의미는 다음과 같습니다.

    • BUCKET_NAME은 버킷의 이름입니다. 예를 들면 my-bucket입니다.
    • CORS_CONFIG_FILE은 2단계에서 만든 JSON 파일의 경로입니다.

XML API

  1. Authorization 헤더에 대한 액세스 토큰을 생성하려면 gcloud CLI가 설치 및 초기화되어 있어야 합니다.

    또는 OAuth 2.0 Playground를 사용하여 액세스 토큰을 만들고 Authorization 헤더에 포함할 수 있습니다.

  2. 적용하려는 CORS 구성을 사용하여 XML 파일을 만듭니다. 샘플 XML 파일은 구성 예시를 참조하세요.

  3. 범위가 ?corsPUT Bucket 요청으로 XML API를 호출하려면 cURL을 사용합니다.

    curl -X PUT --data-binary @CORS_CONFIG_FILE \
    -H "Authorization: Bearer $(gcloud auth print-access-token)" \
    -H "x-goog-project-id: PROJECT_ID" \
    "https://storage.googleapis.com/BUCKET_NAME?cors"

    각 항목의 의미는 다음과 같습니다.

    • BUCKET_NAME은 버킷의 이름입니다. 예를 들면 my-bucket입니다.
    • PROJECT_ID는 버킷과 연결된 프로젝트의 ID입니다. my-project).
    • CORS_CONFIG_FILE은 2단계에서 만든 XML 파일의 경로입니다.

버킷의 CORS 구성을 삭제하려면 빈 CORS 구성을 설정하세요.

버킷의 CORS 구성 보기

버킷의 CORS 구성을 보려면 다음 안내를 따르세요.

콘솔

Google Cloud 콘솔을 사용하여 CORS를 관리할 수 없습니다. 대신 gcloud CLI를 사용하세요.

명령줄

gcloud storage buckets describe 명령어를 --format 플래그와 함께 사용합니다.

gcloud storage buckets describe gs://BUCKET_NAME --format="default(cors_config)"

여기서 BUCKET_NAME은 CORS 구성을 보려는 버킷의 이름입니다. 예를 들면 my-bucket입니다.

클라이언트 라이브러리

클라이언트 라이브러리를 사용하여 버킷의 CORS 구성을 보려면 버킷 메타데이터 표시의 안내를 따라 응답에서 CORS 필드를 찾습니다.

C++

자세한 내용은 Cloud Storage C++ API 참조 문서를 확인하세요.

Cloud Storage에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

namespace gcs = ::google::cloud::storage;
using ::google::cloud::StatusOr;
[](gcs::Client client, std::string const& bucket_name) {
  StatusOr<gcs::BucketMetadata> bucket_metadata =
      client.GetBucketMetadata(bucket_name);
  if (!bucket_metadata) throw std::move(bucket_metadata).status();

  std::cout << "The metadata for bucket " << bucket_metadata->name() << " is "
            << *bucket_metadata << "\n";
}

C#

자세한 내용은 Cloud Storage C# API 참고 문서를 확인하세요.

Cloud Storage에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.


using Google.Apis.Storage.v1.Data;
using Google.Cloud.Storage.V1;
using System;

public class GetBucketMetadataSample
{
    public Bucket GetBucketMetadata(string bucketName = "your-unique-bucket-name")
    {
        var storage = StorageClient.Create();
        var bucket = storage.GetBucket(bucketName, new GetBucketOptions { Projection = Projection.Full });
        Console.WriteLine($"Bucket:\t{bucket.Name}");
        Console.WriteLine($"Acl:\t{bucket.Acl}");
        Console.WriteLine($"Billing:\t{bucket.Billing}");
        Console.WriteLine($"Cors:\t{bucket.Cors}");
        Console.WriteLine($"DefaultEventBasedHold:\t{bucket.DefaultEventBasedHold}");
        Console.WriteLine($"DefaultObjectAcl:\t{bucket.DefaultObjectAcl}");
        Console.WriteLine($"Encryption:\t{bucket.Encryption}");
        if (bucket.Encryption != null)
        {
            Console.WriteLine($"KmsKeyName:\t{bucket.Encryption.DefaultKmsKeyName}");
        }
        Console.WriteLine($"Id:\t{bucket.Id}");
        Console.WriteLine($"Kind:\t{bucket.Kind}");
        Console.WriteLine($"Lifecycle:\t{bucket.Lifecycle}");
        Console.WriteLine($"Location:\t{bucket.Location}");
        Console.WriteLine($"LocationType:\t{bucket.LocationType}");
        Console.WriteLine($"Logging:\t{bucket.Logging}");
        Console.WriteLine($"Metageneration:\t{bucket.Metageneration}");
        Console.WriteLine($"ObjectRetention:\t{bucket.ObjectRetention}");
        Console.WriteLine($"Owner:\t{bucket.Owner}");
        Console.WriteLine($"ProjectNumber:\t{bucket.ProjectNumber}");
        Console.WriteLine($"RetentionPolicy:\t{bucket.RetentionPolicy}");
        Console.WriteLine($"SelfLink:\t{bucket.SelfLink}");
        Console.WriteLine($"StorageClass:\t{bucket.StorageClass}");
        Console.WriteLine($"TimeCreated:\t{bucket.TimeCreated}");
        Console.WriteLine($"Updated:\t{bucket.Updated}");
        Console.WriteLine($"Versioning:\t{bucket.Versioning}");
        Console.WriteLine($"Website:\t{bucket.Website}");
        Console.WriteLine($"TurboReplication:\t{bucket.Rpo}");
        if (bucket.Labels != null)
        {
            Console.WriteLine("Labels:");
            foreach (var label in bucket.Labels)
            {
                Console.WriteLine($"{label.Key}:\t{label.Value}");
            }
        }
        return bucket;
    }
}

Go

자세한 내용은 Cloud Storage Go API 참고 문서를 확인하세요.

Cloud Storage에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

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

	"cloud.google.com/go/storage"
)

// getBucketMetadata gets the bucket metadata.
func getBucketMetadata(w io.Writer, bucketName string) (*storage.BucketAttrs, error) {
	// bucketName := "bucket-name"
	ctx := context.Background()
	client, err := storage.NewClient(ctx)
	if err != nil {
		return nil, fmt.Errorf("storage.NewClient: %w", err)
	}
	defer client.Close()

	ctx, cancel := context.WithTimeout(ctx, time.Second*10)
	defer cancel()
	attrs, err := client.Bucket(bucketName).Attrs(ctx)
	if err != nil {
		return nil, fmt.Errorf("Bucket(%q).Attrs: %w", bucketName, err)
	}
	fmt.Fprintf(w, "BucketName: %v\n", attrs.Name)
	fmt.Fprintf(w, "Location: %v\n", attrs.Location)
	fmt.Fprintf(w, "LocationType: %v\n", attrs.LocationType)
	fmt.Fprintf(w, "StorageClass: %v\n", attrs.StorageClass)
	fmt.Fprintf(w, "Turbo replication (RPO): %v\n", attrs.RPO)
	fmt.Fprintf(w, "TimeCreated: %v\n", attrs.Created)
	fmt.Fprintf(w, "Metageneration: %v\n", attrs.MetaGeneration)
	fmt.Fprintf(w, "PredefinedACL: %v\n", attrs.PredefinedACL)
	if attrs.Encryption != nil {
		fmt.Fprintf(w, "DefaultKmsKeyName: %v\n", attrs.Encryption.DefaultKMSKeyName)
	}
	if attrs.Website != nil {
		fmt.Fprintf(w, "IndexPage: %v\n", attrs.Website.MainPageSuffix)
		fmt.Fprintf(w, "NotFoundPage: %v\n", attrs.Website.NotFoundPage)
	}
	fmt.Fprintf(w, "DefaultEventBasedHold: %v\n", attrs.DefaultEventBasedHold)
	if attrs.RetentionPolicy != nil {
		fmt.Fprintf(w, "RetentionEffectiveTime: %v\n", attrs.RetentionPolicy.EffectiveTime)
		fmt.Fprintf(w, "RetentionPeriod: %v\n", attrs.RetentionPolicy.RetentionPeriod)
		fmt.Fprintf(w, "RetentionPolicyIsLocked: %v\n", attrs.RetentionPolicy.IsLocked)
	}
	fmt.Fprintf(w, "RequesterPays: %v\n", attrs.RequesterPays)
	fmt.Fprintf(w, "VersioningEnabled: %v\n", attrs.VersioningEnabled)
	if attrs.Logging != nil {
		fmt.Fprintf(w, "LogBucket: %v\n", attrs.Logging.LogBucket)
		fmt.Fprintf(w, "LogObjectPrefix: %v\n", attrs.Logging.LogObjectPrefix)
	}
	if attrs.CORS != nil {
		fmt.Fprintln(w, "CORS:")
		for _, v := range attrs.CORS {
			fmt.Fprintf(w, "\tMaxAge: %v\n", v.MaxAge)
			fmt.Fprintf(w, "\tMethods: %v\n", v.Methods)
			fmt.Fprintf(w, "\tOrigins: %v\n", v.Origins)
			fmt.Fprintf(w, "\tResponseHeaders: %v\n", v.ResponseHeaders)
		}
	}
	if attrs.Labels != nil {
		fmt.Fprintf(w, "\n\n\nLabels:")
		for key, value := range attrs.Labels {
			fmt.Fprintf(w, "\t%v = %v\n", key, value)
		}
	}
	return attrs, nil
}

Java

자세한 내용은 Cloud Storage Java API 참고 문서를 확인하세요.

Cloud Storage에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.


import com.google.cloud.storage.Bucket;
import com.google.cloud.storage.BucketInfo;
import com.google.cloud.storage.Storage;
import com.google.cloud.storage.StorageOptions;
import java.util.Map;

public class GetBucketMetadata {
  public static void getBucketMetadata(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();

    // Select all fields. Fields can be selected individually e.g. Storage.BucketField.NAME
    Bucket bucket =
        storage.get(bucketName, Storage.BucketGetOption.fields(Storage.BucketField.values()));

    // Print bucket metadata
    System.out.println("BucketName: " + bucket.getName());
    System.out.println("DefaultEventBasedHold: " + bucket.getDefaultEventBasedHold());
    System.out.println("DefaultKmsKeyName: " + bucket.getDefaultKmsKeyName());
    System.out.println("Id: " + bucket.getGeneratedId());
    System.out.println("IndexPage: " + bucket.getIndexPage());
    System.out.println("Location: " + bucket.getLocation());
    System.out.println("LocationType: " + bucket.getLocationType());
    System.out.println("Metageneration: " + bucket.getMetageneration());
    System.out.println("NotFoundPage: " + bucket.getNotFoundPage());
    System.out.println("RetentionEffectiveTime: " + bucket.getRetentionEffectiveTime());
    System.out.println("RetentionPeriod: " + bucket.getRetentionPeriod());
    System.out.println("RetentionPolicyIsLocked: " + bucket.retentionPolicyIsLocked());
    System.out.println("RequesterPays: " + bucket.requesterPays());
    System.out.println("SelfLink: " + bucket.getSelfLink());
    System.out.println("StorageClass: " + bucket.getStorageClass().name());
    System.out.println("TimeCreated: " + bucket.getCreateTime());
    System.out.println("VersioningEnabled: " + bucket.versioningEnabled());
    System.out.println("ObjectRetention: " + bucket.getObjectRetention());
    if (bucket.getLabels() != null) {
      System.out.println("\n\n\nLabels:");
      for (Map.Entry<String, String> label : bucket.getLabels().entrySet()) {
        System.out.println(label.getKey() + "=" + label.getValue());
      }
    }
    if (bucket.getLifecycleRules() != null) {
      System.out.println("\n\n\nLifecycle Rules:");
      for (BucketInfo.LifecycleRule rule : bucket.getLifecycleRules()) {
        System.out.println(rule);
      }
    }
  }
}

Node.js

자세한 내용은 Cloud Storage Node.js API 참고 문서를 확인하세요.

Cloud Storage에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

// Imports the Google Cloud client library
const {Storage} = require('@google-cloud/storage');

// Creates a client
const storage = new Storage();

async function getBucketMetadata() {
  /**
   * TODO(developer): Uncomment the following lines before running the sample.
   */
  // The ID of your GCS bucket
  // const bucketName = 'your-unique-bucket-name';

  // Get Bucket Metadata
  const [metadata] = await storage.bucket(bucketName).getMetadata();

  console.log(JSON.stringify(metadata, null, 2));
}

PHP

자세한 내용은 Cloud Storage PHP API 참고 문서를 확인하세요.

Cloud Storage에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

use Google\Cloud\Storage\StorageClient;

/**
 * Get bucket metadata.
 *
 * @param string $bucketName The name of your Cloud Storage bucket.
 *        (e.g. 'my-bucket')
 */
function get_bucket_metadata(string $bucketName): void
{
    $storage = new StorageClient();
    $bucket = $storage->bucket($bucketName);
    $info = $bucket->info();

    printf('Bucket Metadata: %s' . PHP_EOL, print_r($info));
}

Python

자세한 내용은 Cloud Storage Python API 참고 문서를 확인하세요.

Cloud Storage에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.


from google.cloud import storage


def bucket_metadata(bucket_name):
    """Prints out a bucket's metadata."""
    # bucket_name = 'your-bucket-name'

    storage_client = storage.Client()
    bucket = storage_client.get_bucket(bucket_name)

    print(f"ID: {bucket.id}")
    print(f"Name: {bucket.name}")
    print(f"Storage Class: {bucket.storage_class}")
    print(f"Location: {bucket.location}")
    print(f"Location Type: {bucket.location_type}")
    print(f"Cors: {bucket.cors}")
    print(f"Default Event Based Hold: {bucket.default_event_based_hold}")
    print(f"Default KMS Key Name: {bucket.default_kms_key_name}")
    print(f"Metageneration: {bucket.metageneration}")
    print(
        f"Public Access Prevention: {bucket.iam_configuration.public_access_prevention}"
    )
    print(f"Retention Effective Time: {bucket.retention_policy_effective_time}")
    print(f"Retention Period: {bucket.retention_period}")
    print(f"Retention Policy Locked: {bucket.retention_policy_locked}")
    print(f"Object Retention Mode: {bucket.object_retention_mode}")
    print(f"Requester Pays: {bucket.requester_pays}")
    print(f"Self Link: {bucket.self_link}")
    print(f"Time Created: {bucket.time_created}")
    print(f"Versioning Enabled: {bucket.versioning_enabled}")
    print(f"Labels: {bucket.labels}")

Ruby

자세한 내용은 Cloud Storage Ruby API 참고 문서를 확인하세요.

Cloud Storage에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

def get_bucket_metadata 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

  puts "ID:                       #{bucket.id}"
  puts "Name:                     #{bucket.name}"
  puts "Storage Class:            #{bucket.storage_class}"
  puts "Location:                 #{bucket.location}"
  puts "Location Type:            #{bucket.location_type}"
  puts "Cors:                     #{bucket.cors}"
  puts "Default Event Based Hold: #{bucket.default_event_based_hold?}"
  puts "Default KMS Key Name:     #{bucket.default_kms_key}"
  puts "Logging Bucket:           #{bucket.logging_bucket}"
  puts "Logging Prefix:           #{bucket.logging_prefix}"
  puts "Metageneration:           #{bucket.metageneration}"
  puts "Retention Effective Time: #{bucket.retention_effective_at}"
  puts "Retention Period:         #{bucket.retention_period}"
  puts "Retention Policy Locked:  #{bucket.retention_policy_locked?}"
  puts "Requester Pays:           #{bucket.requester_pays}"
  puts "Self Link:                #{bucket.api_url}"
  puts "Time Created:             #{bucket.created_at}"
  puts "Versioning Enabled:       #{bucket.versioning?}"
  puts "Index Page:               #{bucket.website_main}"
  puts "Not Found Page:           #{bucket.website_404}"
  puts "Labels:"
  bucket.labels.each do |key, value|
    puts " - #{key} = #{value}"
  end
  puts "Lifecycle Rules:"
  bucket.lifecycle.each do |rule|
    puts "#{rule.action} - #{rule.storage_class} - #{rule.age} - #{rule.matches_storage_class}"
  end
end

REST API

JSON API

  1. Authorization 헤더에 대한 액세스 토큰을 생성하려면 gcloud CLI가 설치 및 초기화되어 있어야 합니다.

    또는 OAuth 2.0 Playground를 사용하여 액세스 토큰을 만들고 Authorization 헤더에 포함할 수 있습니다.

  2. cURL을 사용하여 GET 버킷 요청으로 JSON API를 호출합니다.

    curl -X GET \
        -H "Authorization: Bearer $(gcloud auth print-access-token)" \
        "https://storage.googleapis.com/storage/v1/b/BUCKET_NAME?fields=cors"

    여기서 BUCKET_NAME은 관련 버킷의 이름입니다. 예를 들면 my-bucket입니다.

XML API

  1. Authorization 헤더에 대한 액세스 토큰을 생성하려면 gcloud CLI가 설치 및 초기화되어 있어야 합니다.

    또는 OAuth 2.0 Playground를 사용하여 액세스 토큰을 만들고 Authorization 헤더에 포함할 수 있습니다.

  2. cURL을 사용하여 ?cors로 범위가 지정된 GET 버킷 요청으로 XML API를 호출합니다.

    curl -X GET \
      -H "Authorization: Bearer $(gcloud auth print-access-token)" \
      "https://storage.googleapis.com/BUCKET_NAME?cors"

    여기서 BUCKET_NAME은 관련 버킷의 이름입니다. 예를 들면 my-bucket입니다.

CORS 요청 문제 해결

다른 출처에서 Cloud Storage 버킷에 액세스할 때 예상치 못한 동작이 발생할 경우 다음 단계를 시도하세요.

  1. 대상 버킷에서 CORS 구성을 검토합니다. CORS 구성 항목이 여러 개 있으면 문제 해결에 사용하는 요청 값이 단일 CORS 구성 항목의 값에 매핑되어야 합니다.

  2. CORS 요청을 허용하지 않는 storage.cloud.google.com 엔드포인트 요청을 수행하지 않는지 확인합니다. CORS가 지원되는 엔드포인트에 대한 자세한 내용은 Cloud Storage CORS 지원을 참조하세요.

  3. 원하는 도구를 사용하여 요청 및 응답을 검토합니다. Chrome 브라우저에서는 표준 개발자 도구를 사용하여 이 정보를 볼 수 있습니다.

    1. 브라우저 툴바에서 Chrome 메뉴()를 클릭합니다.
    2. 추가 도구 > 개발자 도구를 선택합니다.
    3. 네트워크 탭을 클릭합니다.
    4. 애플리케이션이나 명령줄에서 요청을 보냅니다.
    5. 네트워크 활동을 표시하는 창에서 요청을 찾습니다.
    6. 이름 열에서 요청에 해당하는 이름을 클릭합니다.
    7. 응답 헤더를 보려면 헤더 탭을 클릭하고, 응답 내용을 보려면 응답 탭을 클릭합니다.

    응답 및 요청이 보이지 않으면 이전에 실패한 실행 전 요청 시도를 브라우저가 캐시한 것일 수도 있습니다. 브라우저의 캐시를 지우면 실행 전 캐시도 지워집니다. 그렇지 않은 경우 CORS 구성의 MaxAgeSec 값을 더 낮은 값으로 설정하고(값을 지정하지 않으면 기본값은 1,800(30분)), 이전의 MaxAgeSec이 얼마나 길었는지 관계없이 요청을 다시 시도합니다. 그러면 새로운 CORS 구성을 가져오고 캐시 항목을 삭제하는 새로운 실행 전 요청이 수행됩니다. 문제를 디버깅한 후에 MaxAgeSec을 다시 더 높은 값으로 올려서 버킷에 대한 실행 전 트래픽을 줄입니다.

  4. 요청에 Origin 헤더가 있고, 이 헤더 값이 버킷의 CORS 구성에서 최소한 하나의 Origins 값과 일치하는지 확인합니다. 스키마, 호스트, 포트의 값이 정확히 일치해야 합니다. 허용되는 일치의 몇 가지 예시는 다음과 같습니다.

    • http://origin.example.comhttp://origin.example.com:80과 일치하지만(80이 기본 HTTP 포트이기 때문) https://origin.example.com, http://origin.example.com:8080, http://origin.example.com:5151 또는 http://sub.origin.example.com과는 일치하지 않습니다.

    • https://example.com:443https://example.com과 일치하지만 http://example.com 또는 http://example.com:443과는 일치하지 않습니다.

    • http://localhost:8080http://localhost:5555 또는 http://localhost.example.com:8080가 아니라 정확히 http://localhost:8080과 일치합니다.

  5. 요청의 HTTP 메서드(단순 요청인 경우) 또는 Access-Control-Request-Method에 지정된 메서드(실행 전 요청인 경우)가 버킷의 CORS 구성에서 최소한 하나의 Methods 값과 일치하는지 확인합니다.

  6. 실행 전 요청인 경우 하나 이상의 Access-Control-Request-Header 헤더를 포함하는지 확인합니다. 그렇다면 각 Access-Control-Request-Header 값이 버킷의 CORS 구성에 있는 ResponseHeader 값과 일치하는지 확인합니다. 실행 전 요청이 성공하고 응답에 CORS 헤더를 포함하려면 Access-Control-Request-Header에 명명된 모든 헤더가 CORS 구성에 있어야 합니다.

다음 단계

  • 버킷에서 CORS 구성을 삭제하는 예시를 포함하여 CORS 구성 예시 살펴보기
  • CORS 자세히 알아보기