Configuration du partage des ressources entre origines multiples (CORS) - Amazon Simple Storage Service

Les traductions sont fournies par des outils de traduction automatique. En cas de conflit entre le contenu d'une traduction et celui de la version originale en anglais, la version anglaise prévaudra.

Configuration du partage des ressources entre origines multiples (CORS)

Le partage des ressources cross-origin (CORS) définit un moyen pour les applications Web clientes chargées dans un domaine particulier d’interagir avec les ressources d’un autre domaine. Le CORS vous permet de créer de riches applications web côté client avec Amazon S3 et d’autoriser de manière sélective un accès cross-origin à vos ressources Amazon S3.

Cette section explique comment activer CORS à l'aide de la console Amazon S3, de l'API REST Amazon S3 et du AWS SDKs. Pour configurer le compartiment afin d’autoriser les demandes entre origines multiples, vous devez ajouter une configuration CORS au compartiment. Une configuration CORS est un document qui définit les règles identifiant les origines auxquelles vous autorisez l’accès au compartiment, les opérations (méthodes HTTP) prises en charge pour chaque origine, et d’autres informations propres aux opérations. Dans la console S3, la configuration CORS doit être un document JSON.

Pour obtenir un exemple de configurations CORS en JSON et XML, consultez Éléments d’une configuration CORS.

Cette section explique comment utiliser la console Amazon S3 pour ajouter une configuration CORS (partage des ressources cross-origin) à un compartiment S3.

Lorsque vous activez CORS sur le bucket, les listes de contrôle d'accès (ACLs) et les autres politiques d'autorisation d'accès continuent de s'appliquer.

Important

Dans la console S3, la configuration CORS doit être de type JSON. Pour obtenir des exemples de configurations CORS en JSON et XML, consultez Éléments d’une configuration CORS.

Pour ajouter une configuration CORS à un compartiment S3
  1. Connectez-vous à la console Amazon S3 AWS Management Console et ouvrez-la à l'adresse https://console.aws.amazon.com/s3/.

  2. Dans le volet de navigation de gauche, choisissez Compartiments à usage général.

  3. Dans la liste des compartiments, choisissez le nom du compartiment pour lequel vous souhaitez créer une politique de compartiment.

  4. Choisissez Permissions.

  5. Dans la section Partage des ressources cross-origin (CORS), choisissez Modifier.

  6. Dans la zone de texte Editeur de configuration CORS, tapez ou copiez et collez une nouvelle configuration CORS, ou modifiez une configuration existante.

    La configuration CORS est un fichier JSON. Le texte que vous saisissez dans l’éditeur doit être dans un format JSON valide. Pour plus d’informations, consultez Éléments d’une configuration CORS.

  7. Sélectionnez Save Changes (Enregistrer les modifications).

    Note

    Amazon S3 affiche l’Amazon Resource Name (ARN) du compartiment en regard du titre Editeur de configuration CORS. Pour plus d'informations sur ARNs, consultez Amazon Resource Names (ARNs) et les espaces de noms de AWS service dans le Référence générale d'Amazon Web Services.

Vous pouvez utiliser le AWS SDK pour gérer le partage de ressources entre origines (CORS) pour un bucket. Pour plus d’informations sur le CORS, consultez Utilisation du partage des ressources entre origines multiples (CORS).

Les exemples suivants :

  • Crée une configuration CORS et définit la configuration sur un compartiment

  • Récupère une configuration et la modifie en ajoutant une règle

  • Ajoute la configuration modifiée au compartiment

  • Supprime la configuration

Java

Pour obtenir des instructions sur la création et le test d'un échantillon fonctionnel, consultez Getting Started dans le guide du AWS SDK for Java développeur.

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); // Retrieve and display the configuration. configuration = s3Client.getBucketCrossOriginConfiguration(bucketName); printCORSConfiguration(configuration); // Add another new rule. List<CORSRule.AllowedMethods> rule3AM = new ArrayList<CORSRule.AllowedMethods>(); rule3AM.add(CORSRule.AllowedMethods.HEAD); CORSRule rule3 = new CORSRule().withId("CORSRule3").withAllowedMethods(rule3AM) .withAllowedOrigins(Arrays.asList("http://www.example.com")); rules = configuration.getRules(); rules.add(rule3); configuration.setRules(rules); s3Client.setBucketCrossOriginConfiguration(bucketName, configuration); // Verify that the new rule was added by checking the number of rules in the // configuration. configuration = s3Client.getBucketCrossOriginConfiguration(bucketName); System.out.println("Expected # of rules = 3, found " + configuration.getRules().size()); // Delete the configuration. s3Client.deleteBucketCrossOriginConfiguration(bucketName); System.out.println("Removed CORS configuration."); // Retrieve and display the configuration to verify that it was // successfully deleted. configuration = s3Client.getBucketCrossOriginConfiguration(bucketName); printCORSConfiguration(configuration); } catch (AmazonServiceException e) { // The call was transmitted successfully, but Amazon S3 couldn't process // it, so it returned an error response. e.printStackTrace(); } catch (SdkClientException e) { // Amazon S3 couldn't be contacted for a response, or the client // couldn't parse the response from Amazon S3. e.printStackTrace(); } } private static void printCORSConfiguration(BucketCrossOriginConfiguration configuration) { if (configuration == null) { System.out.println("Configuration is null."); } else { System.out.println("Configuration has " + configuration.getRules().size() + " rules\n"); for (CORSRule rule : configuration.getRules()) { System.out.println("Rule ID: " + rule.getId()); System.out.println("MaxAgeSeconds: " + rule.getMaxAgeSeconds()); System.out.println("AllowedMethod: " + rule.getAllowedMethods()); System.out.println("AllowedOrigins: " + rule.getAllowedOrigins()); System.out.println("AllowedHeaders: " + rule.getAllowedHeaders()); System.out.println("ExposeHeader: " + rule.getExposedHeaders()); System.out.println(); } } } }
.NET

Pour plus d'informations sur la configuration et l'exécution des exemples de code, consultez Getting Started with the AWS SDK for .NET dans AWS le Guide du développeur du SDK pour .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 rulest=3; found:{0}", configuration.Rules.Count); Console.WriteLine(); Console.WriteLine("Pause before configuration delete. To continue, click Enter..."); Console.ReadKey(); // Delete the configuration. await DeleteCORSConfigurationAsync(); // Retrieve a nonexistent configuration. configuration = await RetrieveCORSConfigurationAsync(); } catch (AmazonS3Exception e) { Console.WriteLine("Error encountered on server. Message:'{0}' when writing an object", e.Message); } catch (Exception e) { Console.WriteLine("Unknown encountered on server. Message:'{0}' when writing an object", e.Message); } } static async Task PutCORSConfigurationAsync(CORSConfiguration configuration) { PutCORSConfigurationRequest request = new PutCORSConfigurationRequest { BucketName = bucketName, Configuration = configuration }; var response = await s3Client.PutCORSConfigurationAsync(request); } static async Task<CORSConfiguration> RetrieveCORSConfigurationAsync() { GetCORSConfigurationRequest request = new GetCORSConfigurationRequest { BucketName = bucketName }; var response = await s3Client.GetCORSConfigurationAsync(request); var configuration = response.Configuration; PrintCORSRules(configuration); return configuration; } static async Task DeleteCORSConfigurationAsync() { DeleteCORSConfigurationRequest request = new DeleteCORSConfigurationRequest { BucketName = bucketName }; await s3Client.DeleteCORSConfigurationAsync(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())); } } } }

Pour définir une configuration CORS sur votre compartiment, vous pouvez utiliser AWS Management Console. Si l’application l’exige, vous pouvez également envoyer directement des demandes REST. Les sections suivantes de la Référence d’API Amazon Simple Storage Service décrivent les actions de l’API REST liées à la configuration CORS :