Utilisation PutBucketCors avec un AWS SDK ou une CLI - AWS Exemples de code SDK

D'autres exemples de AWS SDK sont disponibles dans le référentiel AWS Doc SDK Examples GitHub .

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.

Utilisation PutBucketCors avec un AWS SDK ou une CLI

Les exemples de code suivants montrent comment utiliserPutBucketCors.

.NET
AWS SDK for .NET
Note

Il y en a plus sur GitHub. Trouvez l'exemple complet et découvrez comment le configurer et l'exécuter dans le référentiel d'exemples de code AWS.

/// <summary> /// Add CORS configuration to the Amazon S3 bucket. /// </summary> /// <param name="client">The initialized Amazon S3 client object used /// to apply the CORS configuration to an Amazon S3 bucket.</param> /// <param name="configuration">The CORS configuration to apply.</param> private static async Task PutCORSConfigurationAsync(AmazonS3Client client, CORSConfiguration configuration) { PutCORSConfigurationRequest request = new PutCORSConfigurationRequest() { BucketName = BucketName, Configuration = configuration, }; _ = await client.PutCORSConfigurationAsync(request); }
  • Pour plus de détails sur l'API, reportez-vous PutBucketCorsà la section Référence des AWS SDK for .NET API.

CLI
AWS CLI

L'exemple suivant active PUTPOST, et les DELETE demandes provenant de www.example.com, et active les GET demandes provenant de n'importe quel domaine :

aws s3api put-bucket-cors --bucket MyBucket --cors-configuration file://cors.json cors.json: { "CORSRules": [ { "AllowedOrigins": ["http://www.example.com"], "AllowedHeaders": ["*"], "AllowedMethods": ["PUT", "POST", "DELETE"], "MaxAgeSeconds": 3000, "ExposeHeaders": ["x-amz-server-side-encryption"] }, { "AllowedOrigins": ["*"], "AllowedHeaders": ["Authorization"], "AllowedMethods": ["GET"], "MaxAgeSeconds": 3000 } ] }
  • Pour plus de détails sur l'API, reportez-vous PutBucketCorsà la section Référence des AWS CLI commandes.

Java
SDK pour Java 2.x
Note

Il y en a plus sur GitHub. Trouvez l'exemple complet et découvrez comment le configurer et l'exécuter dans le référentiel d'exemples de code AWS.

import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.s3.S3Client; import java.util.ArrayList; import java.util.List; import software.amazon.awssdk.services.s3.model.GetBucketCorsRequest; import software.amazon.awssdk.services.s3.model.GetBucketCorsResponse; import software.amazon.awssdk.services.s3.model.DeleteBucketCorsRequest; import software.amazon.awssdk.services.s3.model.S3Exception; import software.amazon.awssdk.services.s3.model.CORSRule; import software.amazon.awssdk.services.s3.model.CORSConfiguration; import software.amazon.awssdk.services.s3.model.PutBucketCorsRequest; /** * Before running this Java V2 code example, set up your development * environment, including your credentials. * * For more information, see the following documentation topic: * * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html */ public class S3Cors { public static void main(String[] args) { final String usage = """ Usage: <bucketName> <accountId>\s Where: bucketName - The Amazon S3 bucket to upload an object into. accountId - The id of the account that owns the Amazon S3 bucket. """; if (args.length != 2) { System.out.println(usage); System.exit(1); } String bucketName = args[0]; String accountId = args[1]; Region region = Region.US_EAST_1; S3Client s3 = S3Client.builder() .region(region) .build(); setCorsInformation(s3, bucketName, accountId); getBucketCorsInformation(s3, bucketName, accountId); deleteBucketCorsInformation(s3, bucketName, accountId); s3.close(); } public static void deleteBucketCorsInformation(S3Client s3, String bucketName, String accountId) { try { DeleteBucketCorsRequest bucketCorsRequest = DeleteBucketCorsRequest.builder() .bucket(bucketName) .expectedBucketOwner(accountId) .build(); s3.deleteBucketCors(bucketCorsRequest); } catch (S3Exception e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } } public static void getBucketCorsInformation(S3Client s3, String bucketName, String accountId) { try { GetBucketCorsRequest bucketCorsRequest = GetBucketCorsRequest.builder() .bucket(bucketName) .expectedBucketOwner(accountId) .build(); GetBucketCorsResponse corsResponse = s3.getBucketCors(bucketCorsRequest); List<CORSRule> corsRules = corsResponse.corsRules(); for (CORSRule rule : corsRules) { System.out.println("allowOrigins: " + rule.allowedOrigins()); System.out.println("AllowedMethod: " + rule.allowedMethods()); } } catch (S3Exception e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } } public static void setCorsInformation(S3Client s3, String bucketName, String accountId) { List<String> allowMethods = new ArrayList<>(); allowMethods.add("PUT"); allowMethods.add("POST"); allowMethods.add("DELETE"); List<String> allowOrigins = new ArrayList<>(); allowOrigins.add("http://example.com"); try { // Define CORS rules. CORSRule corsRule = CORSRule.builder() .allowedMethods(allowMethods) .allowedOrigins(allowOrigins) .build(); List<CORSRule> corsRules = new ArrayList<>(); corsRules.add(corsRule); CORSConfiguration configuration = CORSConfiguration.builder() .corsRules(corsRules) .build(); PutBucketCorsRequest putBucketCorsRequest = PutBucketCorsRequest.builder() .bucket(bucketName) .corsConfiguration(configuration) .expectedBucketOwner(accountId) .build(); s3.putBucketCors(putBucketCorsRequest); } catch (S3Exception e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } } }
  • Pour plus de détails sur l'API, reportez-vous PutBucketCorsà la section Référence des AWS SDK for Java 2.x API.

JavaScript
SDK pour JavaScript (v3)
Note

Il y en a plus sur GitHub. Trouvez l'exemple complet et découvrez comment le configurer et l'exécuter dans le référentiel d'exemples de code AWS.

Ajoutez une règle CORS.

import { PutBucketCorsCommand, S3Client } from "@aws-sdk/client-s3"; const client = new S3Client({}); // By default, Amazon S3 doesn't allow cross-origin requests. Use this command // to explicitly allow cross-origin requests. export const main = async () => { const command = new PutBucketCorsCommand({ Bucket: "test-bucket", CORSConfiguration: { CORSRules: [ { // Allow all headers to be sent to this bucket. AllowedHeaders: ["*"], // Allow only GET and PUT methods to be sent to this bucket. AllowedMethods: ["GET", "PUT"], // Allow only requests from the specified origin. AllowedOrigins: ["https://www.example.com"], // Allow the entity tag (ETag) header to be returned in the response. The ETag header // The entity tag represents a specific version of the object. The ETag reflects // changes only to the contents of an object, not its metadata. ExposeHeaders: ["ETag"], // How long the requesting browser should cache the preflight response. After // this time, the preflight request will have to be made again. MaxAgeSeconds: 3600, }, ], }, }); try { const response = await client.send(command); console.log(response); } catch (err) { console.error(err); } };
Python
SDK pour Python (Boto3)
Note

Il y en a plus sur GitHub. Trouvez l'exemple complet et découvrez comment le configurer et l'exécuter dans le référentiel d'exemples de code AWS.

class BucketWrapper: """Encapsulates S3 bucket actions.""" def __init__(self, bucket): """ :param bucket: A Boto3 Bucket resource. This is a high-level resource in Boto3 that wraps bucket actions in a class-like structure. """ self.bucket = bucket self.name = bucket.name def put_cors(self, cors_rules): """ Apply CORS rules to the bucket. CORS rules specify the HTTP actions that are allowed from other domains. :param cors_rules: The CORS rules to apply. """ try: self.bucket.Cors().put(CORSConfiguration={"CORSRules": cors_rules}) logger.info( "Put CORS rules %s for bucket '%s'.", cors_rules, self.bucket.name ) except ClientError: logger.exception("Couldn't put CORS rules for bucket %s.", self.bucket.name) raise
  • Pour plus de détails sur l'API, consultez PutBucketCorsle AWS manuel de référence de l'API SDK for Python (Boto3).

Ruby
Kit SDK pour Ruby
Note

Il y en a plus sur GitHub. Trouvez l'exemple complet et découvrez comment le configurer et l'exécuter dans le référentiel d'exemples de code AWS.

require "aws-sdk-s3" # Wraps Amazon S3 bucket CORS configuration. class BucketCorsWrapper attr_reader :bucket_cors # @param bucket_cors [Aws::S3::BucketCors] A bucket CORS object configured with an existing bucket. def initialize(bucket_cors) @bucket_cors = bucket_cors end # Sets CORS rules on a bucket. # # @param allowed_methods [Array<String>] The types of HTTP requests to allow. # @param allowed_origins [Array<String>] The origins to allow. # @returns [Boolean] True if the CORS rules were set; otherwise, false. def set_cors(allowed_methods, allowed_origins) @bucket_cors.put( cors_configuration: { cors_rules: [ { allowed_methods: allowed_methods, allowed_origins: allowed_origins, allowed_headers: %w[*], max_age_seconds: 3600 } ] } ) true rescue Aws::Errors::ServiceError => e puts "Couldn't set CORS rules for #{@bucket_cors.bucket.name}. Here's why: #{e.message}" false end end
  • Pour plus de détails sur l'API, reportez-vous PutBucketCorsà la section Référence des AWS SDK for Ruby API.