跨源资源共享 (CORS)(摘录)
跨源资源共享 (CORS) 定义了在一个域中加载的客户端 Web 应用程序与另一个域中的资源交互的方式。Amazon S3 中的 CORS 支持让您可以使用 Amazon S3 构建丰富的客户端 Web 应用程序,同时让您可以选择性地允许跨源访问您的 Amazon S3 资源。
本部分提供 CORS 概述。副主题介绍您如何通过使用 Amazon S3 控制台或以编程方式使用 Amazon S3 REST API 和 AWS 开发工具包来启用 CORS。
跨源资源共享:使用案例场景
以下是有关使用 CORS 的示例场景:
-
场景 1:假设您在名为
website的 Amazon S3 存储桶中托管网站 (如在 Amazon S3 上托管静态网站中所述)。您的用户加载了网站终端节点http://website.s3-website-us-east-1.amazonaws.com。现在,您想要使用存储的网页上 (存储在此存储桶中) 的 JavaScript,以使用该存储桶的 Amazon S3 API 终端节点website.s3.amazonaws.com向同一存储桶发送经身份验证的 GET 和 PUT 请求。浏览器通常会阻止 JavaScript 允许这些请求,但借助 CORS,您可以配置您的存储桶以显式支持来自website.s3-website-us-east-1.amazonaws.com的跨源请求。 -
场景 2:假设您想要托管来自您的 S3 存储桶的 Web 字体。浏览器会再次要求对正在加载的 Web 字体进行 CORS 检查 (也称为预检),因此您应该配置托管此 Web 字体的存储桶以允许任意源发送这些请求。
如何在我的存储桶上配置 CORS?
要将您的存储桶配置为允许跨源请求,您可以创建一个 CORS 配置,即一个 XML 文档,其中包含一些规则,它们能够识别您允许访问存储桶的源、每个源支持的操作 (HTTP 方法),以及其他特定操作的信息。
您可以向配置添加最多 100 条规则。通过编程方式或者使用 控制台将 XML 文档作为 cors 子资源 添加到存储桶 Amazon S3。有关更多信息,请参阅 允许跨源资源共享 (CORS)。
您可以使用自己的域 (例如 example1.com) 提供内容,而不是通过使用 Amazon S3 网站终端节点来访问网站。有关如何使用您自己的域的信息,请参阅示例:使用自定义域设置静态网站。以下示例 cors 配置具有三个规则,这些规则被指定为 CORSRule 元素:
-
第一个规则允许来自
https://www.example1.com源的跨源 PUT、POST 和 DELETE 请求。该规则还通过Access-Control-Request-Headers标头允许预检 OPTIONS 请求中的所有标头。作为对任何预检 OPTIONS 请求的响应,Amazon S3 将返回请求的任意标头。 -
第二个规则允许与第一个规则具有相同的跨源请求,但第二个规则应用于另一个源
https://www.example2.com。 -
第三个规则允许来自所有源的跨源 GET 请求。“*”通配符字符是指所有的源。
<CORSConfiguration> <CORSRule> <AllowedOrigin>http://www.example1.com</AllowedOrigin> <AllowedMethod>PUT</AllowedMethod> <AllowedMethod>POST</AllowedMethod> <AllowedMethod>DELETE</AllowedMethod> <AllowedHeader>*</AllowedHeader> </CORSRule> <CORSRule> <AllowedOrigin>http://www.example2.com</AllowedOrigin> <AllowedMethod>PUT</AllowedMethod> <AllowedMethod>POST</AllowedMethod> <AllowedMethod>DELETE</AllowedMethod> <AllowedHeader>*</AllowedHeader> </CORSRule> <CORSRule> <AllowedOrigin>*</AllowedOrigin> <AllowedMethod>GET</AllowedMethod> </CORSRule> </CORSConfiguration>
CORS 配置还允许可选的配置参数,如下面的 CORS 配置所示。在本示例中,下面的 CORS 配置允许来自 http://www.example.com 源的跨源 PUT、POST 和 DELETE 请求。
<CORSConfiguration> <CORSRule> <AllowedOrigin>http://www.example.com</AllowedOrigin> <AllowedMethod>PUT</AllowedMethod> <AllowedMethod>POST</AllowedMethod> <AllowedMethod>DELETE</AllowedMethod> <AllowedHeader>*</AllowedHeader> <MaxAgeSeconds>3000</MaxAgeSeconds> <ExposeHeader>x-amz-server-side-encryption</ExposeHeader> <ExposeHeader>x-amz-request-id</ExposeHeader> <ExposeHeader>x-amz-id-2</ExposeHeader> </CORSRule> </CORSConfiguration>
上述配置中的 CORSRule 元素包括以下可选元素:
-
MaxAgeSeconds- 指定在 Amazon S3 针对特定资源的预检 OPTIONS 请求做出响应后,浏览器缓存该响应的时间 (以秒为单位) (在本示例中,为 3000 秒)。通过缓存响应,在需要重复原始请求时,浏览器无需向 Amazon S3 发送预检请求。 -
ExposeHeader– 识别可允许客户从应用程序 (例如,从 JavaScriptXMLHttpRequest对象) 进行访问的响应标头 (在本示例中,为x-amz-server-side-encryption、x-amz-request-id和x-amz-id-2)。
AllowedMethod 元素
在 CORS 配置中,您可以为 AllowedMethod 元素指定以下值。
-
GET
-
PUT
-
POST
-
DELETE
-
HEAD
AllowedOrigin 元素
在 AllowedOrigin 元素中,指定要允许从其发送跨源请求的源,例如http://www.example.com。源字符串可包含至少一个 * 通配符字符,例如 http://*.example.com。您可以选择将 * 指定为源,以允许所有源发送跨源请求。您还可以指定 https 只允许安全的源。
AllowedHeader 元素
AllowedHeader 元素通过 Access-Control-Request-Headers 标头指定预检请求中允许哪些标头。Access-Control-Request-Headers 标头中的每个标头名称必须匹配规则中的相应条目。Amazon S3 将仅发送请求的响应中允许的标头。有关可以在发送至 Amazon S3 的请求中使用的标头示例列表,请参阅 Amazon Simple Storage Service API Reference 指南中的常用请求标头。
规则中的每个 AllowedHeader 字符串可以包含至少一个 * 通配符字符。例如,<AllowedHeader>x-amz-*</AllowedHeader> 将允许所有特定于 Amazon 的标头。
ExposeHeader 元素
每个 ExposeHeader 元素标识您希望客户能够从其应用程序 (例如,从 JavaScript XMLHttpRequest 对象) 进行访问的响应标头。有关常用 Amazon S3 响应标头的列表,请参阅 Amazon Simple Storage Service API Reference 指南中的常用响应标头。
MaxAgeSeconds 元素
MaxAgeSeconds 元素指定在预检请求被资源、HTTP 方法和源识别之后,浏览器将为预检请求缓存响应的时间 (以秒为单位)。
Amazon S3 如何评估针对存储桶的 CORS 配置?
Amazon S3 收到来自浏览器的预检请求后,它将为存储桶评估 CORS 配置,并使用第一个匹配传入浏览器请求的 CORSRule 规则来实现跨源请求。要使规则实现匹配,必须满足以下条件:
-
请求的
Origin标头必须匹配AllowedOrigin元素。 -
预检
OPTIONS请求中的请求方法 (例如,GET 或 PUT) 或Access-Control-Request-Method标头必须是某个AllowedMethod元素。 -
在预检请求中,请求的
Access-Control-Request-Headers标头中列出的每个标头必须匹配AllowedHeader元素。
注意
使存储桶允许 CORS 后,ACL 和策略仍适用。
允许跨源资源共享 (CORS)
通过使用 AWS 管理控制台、REST API、或 AWS 开发工具包对您的存储桶设置 CORS 配置,来实现跨源资源共享。
主题
1.使用 AWS 管理控制台实现跨源资源共享 (CORS).
如何允许跨CORS的跨域资源共享?
本节介绍如何使用Amazon S3控制台将跨源资源共享(CORS)配置添加到S3存储桶。CORS允许在一个域中加载的客户端Web应用程序与另一个域中的资源进行交互。
要配置您的存储桶以允许跨域请求,请将CORS配置添加到存储桶。CORS配置是一个XML文档,它定义了一些规则,这些规则将标识您将允许访问存储桶的起源,每个源支持的操作(HTTP方法)以及其他操作特定的信息。有关CORS的更多信息,请参阅Amazon Simple Storage Service开发人员指南中的 跨源资源共享(CORS)。
在存储桶上启用CORS时,访问控制列表(ACL)和其他访问权限策略将继续应用。
将CORS配置添加到S3存储桶
-
登录AWS管理控制台并通过以下网址打开Amazon S3控制台:https://console.amazonaws.cn/s3/。
-
在“ 存储桶名称”列表中,选择要为其创建存储桶策略的存储桶的名称。

-
选择权限,然后选择 CORS配置。

-
在CORS配置编辑器文本框中,键入或复制并粘贴新的CORS配置,或编辑现有配置。CORS配置是一个XML文件。您在编辑器中键入的文本必须是有效的XML。

选择保存。
注意
Amazon S3显示CORS配置编辑器标题旁边存储桶的Amazon资源名称(ARN)。有关ARN的更多信息,请参阅Amazon Web Services一般参考中的Amazon 资源名称(ARN)和AWS服务名称空间。使用AWS
2.SDK for Java实现跨源资源共享 (CORS)
使用AWS SDK for Java实现跨源资源共享(CORS)
您可以使用AWS SDK for Java管理存储桶的跨源资源共享(CORS)。
本节将为下面的任务提供示例代码段,后跟演示所有任务的完整示例程序。
-
创建一个Amazon S3客户端类的实例
-
创建CORS配置并将其添加到存储桶
-
更新现有CORS配置
跨源资源共享方法
|
构建 |
|
|
设置要应用于存储桶的CORS配置。如果指定的存储桶已存在一个配置,新的配置将替换现有配置。 |
|
|
检索指定存储桶的CORS配置。如果没有为存储桶设置任何配置,则响应中的 |
|
|
删除指定存储桶的CORS配置。 |
有关AWS SDK for Java API的更多信息,请参阅AWS SDK for Java API参考。
创建一个Amazon S3客户端类的实例
的下面段代码将为名为CORS_JavaSDK的类创建³³新的AmazonS3Client实例。示例本。AwsCredentials.properties将从文件检索accessKey状语从句:secretKey的值。
AmazonS3Client client;
client = new AmazonS3Client(new ProfileCredentialsProvider());
创建CORS配置并将其添加到存储桶
将CORS配置添加到存储桶的步骤:
-
用于创建³³说明规则的
CORSRule对象。 -
创建³³
BucketCrossOriginConfiguration对象,然后将规则添加到配置对象。 -
通过调用
client.setBucketCrossOriginConfiguration方法,将CORS配置添加到存储桶。
下面的代码段将创建两个规则,CORSRule1和CORSRule2,将然后每个规则添加到rules数组。接着,使用通过rules数组,将规则添加到存储桶bucketName。
// Add a sample configuration BucketCrossOriginConfiguration configuration = new BucketCrossOriginConfiguration(); List<CORSRule> rules = new ArrayList<CORSRule>(); CORSRule rule1 = new CORSRule() .withId("CORSRule1") .withAllowedMethods(Arrays.asList(new CORSRule.AllowedMethods[] { CORSRule.AllowedMethods.PUT, CORSRule.AllowedMethods.POST, CORSRule.AllowedMethods.DELETE})) .withAllowedOrigins(Arrays.asList(new String[] {"http://*.example.com"})); CORSRule rule2 = new CORSRule() .withId("CORSRule2") .withAllowedMethods(Arrays.asList(new CORSRule.AllowedMethods[] { CORSRule.AllowedMethods.GET})) .withAllowedOrigins(Arrays.asList(new String[] {"*"})) .withMaxAgeSeconds(3000) .withExposedHeaders(Arrays.asList(new String[] {"x-amz-server-side-encryption"})); configuration.setRules(Arrays.asList(new CORSRule[] {rule1, rule2})); // Save the configuration client.setBucketCrossOriginConfiguration(bucketName, configuration);
更新现有CORS配置
更新现有CORS配置的步骤
-
通过调用
client.getBucketCrossOriginConfiguration方法获取CORS配置。 -
通过在规则列表中添加或删除规则,更新配置信息。
-
调用通过
client.getBucketCrossOriginConfiguration方法,向存储桶添加配置。
下面的代码段将获取现有的配置,然后添加一个ID为NewRule的新规则。
// Get configuration. BucketCrossOriginConfiguration configuration = client.getBucketCrossOriginConfiguration(bucketName); // Add new rule. CORSRule rule3 = new CORSRule() .withId("CORSRule3") .withAllowedMethods(Arrays.asList(new CORSRule.AllowedMethods[] { CORSRule.AllowedMethods.HEAD})) .withAllowedOrigins(Arrays.asList(new String[] {"http://www.example.com"})); List<CORSRule> rules = configuration.getRules(); rules.add(rule3); configuration.setRules(rules); // Save configuration. client.setBucketCrossOriginConfiguration(bucketName, configuration);
例程列表
以下Java程序集成了上述任务。
有关创建和测试有效示例的信息,请参阅测试Java代码示例。
import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import com.amazonaws.auth.profile.ProfileCredentialsProvider; import com.amazonaws.services.s3.AmazonS3Client; import com.amazonaws.services.s3.model.BucketCrossOriginConfiguration; import com.amazonaws.services.s3.model.CORSRule; public class Cors { /** * @param args * @throws IOException */ public static AmazonS3Client client; public static String bucketName = "***provide bucket name***"; public static void main(String[] args) throws IOException { client = new AmazonS3Client(new ProfileCredentialsProvider()); // Create a new configuration request and add two rules BucketCrossOriginConfiguration configuration = new BucketCrossOriginConfiguration(); List<CORSRule> rules = new ArrayList<CORSRule>(); CORSRule rule1 = new CORSRule() .withId("CORSRule1") .withAllowedMethods(Arrays.asList(new CORSRule.AllowedMethods[] { CORSRule.AllowedMethods.PUT, CORSRule.AllowedMethods.POST, CORSRule.AllowedMethods.DELETE})) .withAllowedOrigins(Arrays.asList(new String[] {"http://*.example.com"})); CORSRule rule2 = new CORSRule() .withId("CORSRule2") .withAllowedMethods(Arrays.asList(new CORSRule.AllowedMethods[] { CORSRule.AllowedMethods.GET})) .withAllowedOrigins(Arrays.asList(new String[] {"*"})) .withMaxAgeSeconds(3000) .withExposedHeaders(Arrays.asList(new String[] {"x-amz-server-side-encryption"})); configuration.setRules(Arrays.asList(new CORSRule[] {rule1, rule2})); // Add the configuration to the bucket. client.setBucketCrossOriginConfiguration(bucketName, configuration); // Retrieve an existing configuration. configuration = client.getBucketCrossOriginConfiguration(bucketName); printCORSConfiguration(configuration); // Add a new rule. CORSRule rule3 = new CORSRule() .withId("CORSRule3") .withAllowedMethods(Arrays.asList(new CORSRule.AllowedMethods[] { CORSRule.AllowedMethods.HEAD})) .withAllowedOrigins(Arrays.asList(new String[] {"http://www.example.com"})); rules = configuration.getRules(); rules.add(rule3); configuration.setRules(rules); client.setBucketCrossOriginConfiguration(bucketName, configuration); System.out.format("Added another rule: %s\n", rule3.getId()); // Verify that the new rule was added. configuration = client.getBucketCrossOriginConfiguration(bucketName); System.out.format("Expected # of rules = 3, found %s", configuration.getRules().size()); // Delete the configuration. client.deleteBucketCrossOriginConfiguration(bucketName); // Try to retrieve configuration. configuration = client.getBucketCrossOriginConfiguration(bucketName); System.out.println("\nRemoved CORS configuration."); printCORSConfiguration(configuration); } static void printCORSConfiguration(BucketCrossOriginConfiguration configuration) { if (configuration == null) { System.out.println("\nConfiguration is null."); return; } System.out.format("\nConfiguration has %s rules:\n", configuration.getRules().size()); for (CORSRule rule : configuration.getRules()) { System.out.format("Rule ID: %s\n", rule.getId()); System.out.format("MaxAgeSeconds: %s\n", rule.getMaxAgeSeconds()); System.out.format("AllowedMethod: %s\n", rule.getAllowedMethods().toArray()); System.out.format("AllowedOrigins: %s\n", rule.getAllowedOrigins()); System.out.format("AllowedHeaders: %s\n", rule.getAllowedHeaders()); System.out.format("ExposeHeader: %s\n", rule.getExposedHeaders()); } } }
3.使用适用于 .NET 的 AWS 开发工具包实现跨源资源共享 (CORS)
使用适用于 .NET 的 AWS 开发工具包实现跨源资源共享 (CORS)
您可以使用适用于 .NET 的 AWS 开发工具包管理存储桶的跨源资源共享 (CORS)。有关 CORS 的更多信息,请参阅 跨源资源共享 (CORS)。
本节将为下表中的任务提供示例代码,后跟完整的示例程序列表。
管理跨源资源共享
管理跨源资源共享
|
1 |
创建 |
|
2 |
创建新的 CORS 配置。 |
|
3 |
检索和修改现有 CORS 配置。 |
|
4 |
向存储桶添加配置。 |
跨源资源共享方法
|
使用 App.config 文件中定义的凭证构建 |
|
|
设置应当应用于存储桶的 CORS 配置。如果指定的存储桶已存在一个配置,新的配置将替换现有配置。 |
|
|
检索指定存储桶的 CORS 配置。如果没有为存储桶设置任何配置,则响应中的 |
|
|
删除指定存储桶的 CORS 配置。 |
有关适用于 .NET 的 AWS 开发工具包 API 的更多信息,请参阅使用 适用于 .NET 的 AWS 开发工具包。
创建 AmazonS3 类的实例
以下示例创建 AmazonS3Client 类的实例。
static IAmazonS3 client; using (client = new AmazonS3Client(Amazon.RegionEndpoint.USWest2))
向存储桶添加 CORS 配置
将 CORS 配置添加到存储桶的步骤:
-
创建用于说明规则的
CORSConfiguration对象。 -
创建可提供存储桶名称和 CORS 配置的
PutCORSConfigurationRequest对象。 -
通过调用
client.PutCORSConfiguration,向存储桶添加 CORS 配置。
以下示例创建两个规则 CORSRule1 和 CORSRule2,然后将每个规则添加到 rules 数组。接着,通过使用 rules 数组,将规则添加到存储桶 bucketName。
// Add a sample configuration 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"} } } }; // Save the configuration PutCORSConfiguration(configuration); static void PutCORSConfiguration(CORSConfiguration configuration) { PutCORSConfigurationRequest request = new PutCORSConfigurationRequest { BucketName = bucketName, Configuration = configuration }; var response = client.PutCORSConfiguration(request); }
更新现有 CORS 配置
更新现有 CORS 配置的步骤
-
通过调用
client.GetCORSConfiguration方法获取 CORS 配置。 -
通过添加或删除规则,更新配置信息。
-
通过调用
client.PutCORSConfiguration方法,向存储桶添加配置。
下面的代码段将获取现有的配置,然后添加一个 ID 为 NewRule 的新规则。
// Get configuration. configuration = GetCORSConfiguration(); // Add new rule. configuration.Rules.Add(new CORSRule { Id = "NewRule", AllowedMethods = new List<string> { "HEAD" }, AllowedOrigins = new List<string> { "http://www.example.com" } }); // Save configuration. PutCORSConfiguration(configuration);
例 程序列表
下面的 C# 程序集成了上述任务。
有关创建和测试有效示例的信息,请参阅 运行 Amazon S3 .NET 代码示例。
using System; using System.Configuration; using System.Collections.Specialized; using System.Net; using Amazon.S3; using Amazon.S3.Model; using Amazon.S3.Util; using System.Diagnostics; using System.Collections.Generic; namespace s3.amazon.com.docsamples { class CORS { static string bucketName = "*** Provide bucket name ***"; static IAmazonS3 client; public static void Main(string[] args) { try { using (client = new AmazonS3Client(Amazon.RegionEndpoint.USWest2)) { // 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 PutCORSConfiguration(configuration); // Retrieve an existing configuration configuration = GetCORSConfiguration(); // 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 PutCORSConfiguration(configuration); // Verify that there are now three rules configuration = GetCORSConfiguration(); Console.WriteLine(); Console.WriteLine("Expected # of rulest=3; found:{0}", configuration.Rules.Count); Console.WriteLine(); Console.WriteLine("Pause before configuration delete. To continue, click Enter..."); Console.ReadKey(); // Delete the configuration DeleteCORSConfiguration(); // Retrieve a nonexistent configuration configuration = GetCORSConfiguration(); Debug.Assert(configuration == null); } Console.WriteLine("Example complete."); } catch (AmazonS3Exception amazonS3Exception) { Console.WriteLine("S3 error occurred. Exception: " + amazonS3Exception.ToString()); Console.ReadKey(); } catch (Exception e) { Console.WriteLine("Exception: " + e.ToString()); Console.ReadKey(); } Console.WriteLine("Press any key to continue..."); Console.ReadKey(); } static void PutCORSConfiguration(CORSConfiguration configuration) { PutCORSConfigurationRequest request = new PutCORSConfigurationRequest { BucketName = bucketName, Configuration = configuration }; var response = client.PutCORSConfiguration(request); } static CORSConfiguration GetCORSConfiguration() { GetCORSConfigurationRequest request = new GetCORSConfigurationRequest { BucketName = bucketName }; var response = client.GetCORSConfiguration(request); var configuration = response.Configuration; PrintCORSRules(configuration); return configuration; } static void DeleteCORSConfiguration() { DeleteCORSConfigurationRequest request = new DeleteCORSConfigurationRequest { BucketName = bucketName }; client.DeleteCORSConfiguration(request); } static void PrintCORSRules(CORSConfiguration configuration) { Console.WriteLine(); if (configuration == null) { Console.WriteLine("\nConfiguration is null"); return; } Console.WriteLine("Configuration has {0} rules:", configuration.Rules.Count); foreach (CORSRule rule in configuration.Rules) { Console.WriteLine("Rule ID: {0}", rule.Id); Console.WriteLine("MaxAgeSeconds: {0}", rule.MaxAgeSeconds); Console.WriteLine("AllowedMethod: {0}", string.Join(", ", rule.AllowedMethods.ToArray())); Console.WriteLine("AllowedOrigins: {0}", string.Join(", ", rule.AllowedOrigins.ToArray())); Console.WriteLine("AllowedHeaders: {0}", string.Join(", ", rule.AllowedHeaders.ToArray())); Console.WriteLine("ExposeHeader: {0}", string.Join(", ", rule.ExposeHeaders.ToArray())); } } } }
4.使用 REST API 允许跨源资源共享 (CORS)
使用 REST API 允许跨源资源共享 (CORS)
您可以使用 AWS 管理控制台对存储桶设置 CORS 配置。如果您的应用程序需要它,您也可以直接发送 REST 请求。Amazon Simple Storage Service API Reference 中的以下各部分介绍与 CORS 配置相关的 REST API 操作:

浙公网安备 33010602011771号