교차 출처 리소스 공유(CORS) 구성
교차 출처 리소스 공유(CORS) 구성
교차 출처 리소스 공유(CORS)는 한 도메인에 로드된 클라이언트 웹 애플리케이션이 다른 도메인의 리소스와 상호작용할 수 있는 방법을 정의해요. CORS 지원을 사용하면 Amazon S3로 풍부한 클라이언트 측 웹 애플리케이션을 만들고, Amazon S3 리소스에 대한 교차 출처 접근을 선택적으로 허용할 수 있어요.
출처: 문서
본문
이 섹션은 Amazon S3 콘솔, Amazon S3 REST API, AWS SDK로 CORS를 활성화하는 방법을 보여줘요. 버킷이 교차 출처 요청을 허용하도록 구성하려면 버킷에 CORS 구성을 추가해요. CORS 구성은 버킷에 접근하도록 허용할 출처, 각 출처에 대해 지원되는 작업(HTTP 메서드), 기타 작업별 정보를 식별하는 규칙을 정의하는 문서예요. S3 콘솔에서 CORS 구성은 JSON 문서여야 해요.
JSON과 XML의 CORS 구성 예시는 CORS 구성 요소를 참고하세요.
이 섹션은 Amazon S3 콘솔로 S3 버킷에 CORS 구성을 추가하는 방법을 설명해요.
버킷에서 CORS를 활성화해도 ACL(접근 제어 목록)과 기타 접근 권한 정책은 계속 적용돼요.
중요 S3 콘솔에서 CORS 구성은 JSON이어야 해요. JSON과 XML의 CORS 구성 예시는 CORS 구성 요소를 참고하세요.
S3 버킷에 CORS 구성을 추가하는 방법은 다음과 같아요.
- AWS Management Console에 로그인하고 https://console.aws.amazon.com/s3/에서 Amazon S3 콘솔을 열어요.
- 왼쪽 탐색 창에서 General purpose buckets를 선택해요.
- 버킷 목록에서 버킷 정책을 만들려는 버킷의 이름을 선택해요.
- Permissions를 선택해요.
- Cross-origin resource sharing (CORS) 섹션에서 Edit를 선택해요.
- CORS configuration editor 텍스트 상자에 새 CORS 구성을 입력하거나 복사해 붙여넣거나, 기존 구성을 편집해요. CORS 구성은 JSON 파일이에요. 편집기에 입력하는 텍스트는 유효한 JSON이어야 해요. 자세한 내용은 CORS 구성 요소를 참고하세요.
- Save changes를 선택해요. 참고: Amazon S3는 CORS configuration editor 제목 옆에 버킷의 ARN(Amazon 리소스 이름)을 표시해요. ARN에 대한 자세한 내용은 Amazon Web Services General Reference의 Amazon 리소스 이름(ARN)과 AWS 서비스 네임스페이스를 참고하세요.
AWS SDK로 버킷의 CORS를 관리할 수 있어요. CORS에 대한 자세한 내용은 교차 출처 리소스 공유(CORS) 사용을 참고하세요.
다음 예시는 다음을 수행해요.
- CORS 구성을 만들고 버킷에 설정해요.
- 구성을 검색하고 규칙을 추가해 수정해요.
- 수정된 구성을 버킷에 추가해요.
- 구성을 삭제해요.
Java — 작업 샘플을 만들고 테스트하는 방법에 대한 자세한 내용은 AWS SDK for Java Developer Guide의 Getting Started를 참고하세요.
import com.amazonaws.AmazonServiceException;
import com.amazonaws.SdkClientException;
import com.amazonaws.auth.profile.ProfileCredentialsProvider;
import com.amazonaws.regions.Regions;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3ClientBuilder;
import com.amazonaws.services.s3.model.BucketCrossOriginConfiguration;
import com.amazonaws.services.s3.model.CORSRule;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class CORS {
public static void main(String[] args) throws IOException {
Regions clientRegion = Regions.DEFAULT_REGION;
String bucketName = "*** Bucket name ***";
// Create two CORS rules.
List<CORSRule.AllowedMethods> rule1AM = new ArrayList<CORSRule.AllowedMethods>();
rule1AM.add(CORSRule.AllowedMethods.PUT);
rule1AM.add(CORSRule.AllowedMethods.POST);
rule1AM.add(CORSRule.AllowedMethods.DELETE);
CORSRule rule1 = new CORSRule().withId("CORSRule1").withAllowedMethods(rule1AM)
.withAllowedOrigins(Arrays.asList("http://*.example.com"));
List<CORSRule.AllowedMethods> rule2AM = new ArrayList<CORSRule.AllowedMethods>();
rule2AM.add(CORSRule.AllowedMethods.GET);
CORSRule rule2 = new CORSRule().withId("CORSRule2").withAllowedMethods(rule2AM)
.withAllowedOrigins(Arrays.asList("*")).withMaxAgeSeconds(3000)
.withExposedHeaders(Arrays.asList("x-amz-server-side-encryption"));
List<CORSRule> rules = new ArrayList<CORSRule>();
rules.add(rule1);
rules.add(rule2);
// Add the rules to a new CORS configuration.
BucketCrossOriginConfiguration configuration = new BucketCrossOriginConfiguration();
configuration.setRules(rules);
try {
AmazonS3 s3Client = AmazonS3ClientBuilder.standard()
.withCredentials(new ProfileCredentialsProvider())
.withRegion(clientRegion)
.build();
// Add the configuration to the bucket.
s3Client.setBucketCrossOriginConfiguration(bucketName, configuration);
System.out.println("Added CORS configuration to bucket: " + bucketName);
// Retrieve the configuration and add a new rule.
BucketCrossOriginConfiguration configuration2 = s3Client.getBucketCrossOriginConfiguration(bucketName);
List<CORSRule> rules2 = configuration2.getRules();
CORSRule rule3 = new CORSRule().withId("CORSRule3")
.withAllowedMethods(Arrays.asList(CORSRule.AllowedMethods.HEAD))
.withAllowedOrigins(Arrays.asList("http://www.example.com"));
rules2.add(rule3);
configuration2.setRules(rules2);
s3Client.setBucketCrossOriginConfiguration(bucketName, configuration2);
System.out.println("Updated CORS configuration to bucket: " + bucketName);
// Delete the configuration.
s3Client.deleteBucketCrossOriginConfiguration(bucketName);
System.out.println("Deleted CORS configuration from bucket: " + bucketName);
} catch (AmazonServiceException e) {
System.err.println(e.getErrorMessage());
System.exit(1);
} catch (SdkClientException e) {
e.printStackTrace();
System.exit(1);
}
}
}
.NET — 코드 예시 설정과 실행에 대한 자세한 내용은 AWS SDK for .NET Developer Guide의 AWS SDK for .NET 시작하기를 참고하세요.
using Amazon;
using Amazon.S3;
using Amazon.S3.Model;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace Amazon.DocSamples.S3
{
class CORSTest
{
private const string bucketName = "*** bucket name ***";
// Specify your bucket region (an example region is shown).
private static readonly RegionEndpoint bucketRegion = RegionEndpoint.USWest2;
private static IAmazonS3 s3Client;
public static void Main()
{
s3Client = new AmazonS3Client(bucketRegion);
CORSConfigTestAsync().Wait();
}
private static async Task CORSConfigTestAsync()
{
try
{
// Create a new configuration request and add two rules
CORSConfiguration configuration = new CORSConfiguration
{
Rules = new System.Collections.Generic.List<CORSRule>
{
new CORSRule
{
Id = "CORSRule1",
AllowedMethods = new List<string> {"PUT", "POST", "DELETE"},
AllowedOrigins = new List<string> {"http://*.example.com"}
},
new CORSRule
{
Id = "CORSRule2",
AllowedMethods = new List<string> {"GET"},
AllowedOrigins = new List<string> {"*"},
MaxAgeSeconds = 3000,
ExposeHeaders = new List<string> {"x-amz-server-side-encryption"}
}
}
};
// Add the configuration to the bucket.
await PutCORSConfigurationAsync(configuration);
// Retrieve an existing configuration.
configuration = await RetrieveCORSConfigurationAsync();
// Add a new rule.
configuration.Rules.Add(new CORSRule
{
Id = "CORSRule3",
AllowedMethods = new List<string> { "HEAD" },
AllowedOrigins = new List<string> { "http://www.example.com" }
});
// Add the configuration to the bucket.
await PutCORSConfigurationAsync(configuration);
// Verify that there are now three rules.
configuration = await RetrieveCORSConfigurationAsync();
Console.WriteLine();
Console.WriteLine("Expected # of rules=3; found:" + configuration.Rules.Count);
}
catch (AmazonS3Exception e)
{
Console.WriteLine("Error encountered. Message:'{0}' when writing an object", e.Message);
}
catch (Exception e)
{
Console.WriteLine("Unknown encountered. Message:'{0}' when writing an object", e.Message);
}
}
private static async Task PutCORSConfigurationAsync(CORSConfiguration configuration)
{
PutCORSConfigurationRequest request = new PutCORSConfigurationRequest
{
BucketName = bucketName,
Configuration = configuration
};
await s3Client.PutCORSConfigurationAsync(request);
Console.WriteLine("Added CORS configuration to bucket: " + bucketName);
}
private static async Task<CORSConfiguration> RetrieveCORSConfigurationAsync()
{
GetCORSConfigurationRequest request = new GetCORSConfigurationRequest
{
BucketName = bucketName
};
return (await s3Client.GetCORSConfigurationAsync(request)).Configuration;
}
}
}
버킷에 CORS 구성을 설정하려면 AWS Management Console을 사용할 수 있어요. 애플리케이션에서 필요하다면 REST 요청을 직접 보낼 수도 있어요. Amazon Simple Storage Service API Reference의 다음 섹션은 CORS 구성과 관련된 REST API 작업을 설명해요.