Gunakan PutBucketCors dengan AWS SDK atau CLI - AWS Contoh Kode SDK

Ada lebih banyak contoh AWS SDK yang tersedia di repo Contoh SDK AWS Doc. GitHub

Terjemahan disediakan oleh mesin penerjemah. Jika konten terjemahan yang diberikan bertentangan dengan versi bahasa Inggris aslinya, utamakan versi bahasa Inggris.

Gunakan PutBucketCors dengan AWS SDK atau CLI

Contoh kode berikut menunjukkan cara menggunakanPutBucketCors.

.NET
AWS SDK for .NET
catatan

Ada lebih banyak tentang GitHub. Temukan contoh lengkapnya dan pelajari cara mengatur dan menjalankannya di AWS Repositori Contoh Kode.

/// <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); }
  • Untuk detail API, lihat PutBucketCorsdi Referensi AWS SDK for .NET API.

CLI
AWS CLI

Contoh berikut memungkinkanPUT,POST, dan DELETE permintaan dari www.example.com, dan memungkinkan GET permintaan dari domain apa pun:

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 } ] }
  • Untuk detail API, lihat PutBucketCorsdi Referensi AWS CLI Perintah.

Java
SDK untuk Java 2.x
catatan

Ada lebih banyak tentang GitHub. Temukan contoh lengkapnya dan pelajari cara mengatur dan menjalankannya di AWS Repositori Contoh Kode.

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); } } }
  • Untuk detail API, lihat PutBucketCorsdi Referensi AWS SDK for Java 2.x API.

JavaScript
SDK untuk JavaScript (v3)
catatan

Ada lebih banyak tentang GitHub. Temukan contoh lengkapnya dan pelajari cara mengatur dan menjalankannya di AWS Repositori Contoh Kode.

Tambahkan aturan 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 untuk Python (Boto3)
catatan

Ada lebih banyak tentang GitHub. Temukan contoh lengkapnya dan pelajari cara mengatur dan menjalankannya di AWS Repositori Contoh Kode.

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
  • Untuk detail API, lihat PutBucketCorsdi AWS SDK for Python (Boto3) Referensi API.

Ruby
SDK untuk Ruby
catatan

Ada lebih banyak tentang GitHub. Temukan contoh lengkapnya dan pelajari cara mengatur dan menjalankannya di AWS Repositori Contoh Kode.

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
  • Untuk detail API, lihat PutBucketCorsdi Referensi AWS SDK for Ruby API.