Use PutBucketCors with an Amazon SDK or CLI - Amazon Simple Storage Service
Services or capabilities described in Amazon Web Services documentation might vary by Region. To see the differences applicable to the China Regions, see Getting Started with Amazon Web Services in China (PDF).

Use PutBucketCors with an Amazon SDK or CLI

The following code examples show how to use PutBucketCors.

.NET
Amazon SDK for .NET
Note

There's more on GitHub. Find the complete example and learn how to set up and run in the Amazon Code Examples Repository.

/// <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); }
  • For API details, see PutBucketCors in Amazon SDK for .NET API Reference.

CLI
Amazon CLI

The following example enables PUT, POST, and DELETE requests from www.example.com, and enables GET requests from any domain:

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 } ] }
  • For API details, see PutBucketCors in Amazon CLI Command Reference.

Java
SDK for Java 2.x
Note

There's more on GitHub. Find the complete example and learn how to set up and run in the Amazon Code Examples Repository.

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); } } }
  • For API details, see PutBucketCors in Amazon SDK for Java 2.x API Reference.

JavaScript
SDK for JavaScript (v3)
Note

There's more on GitHub. Find the complete example and learn how to set up and run in the Amazon Code Examples Repository.

Add a CORS rule.

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 for Python (Boto3)
Note

There's more on GitHub. Find the complete example and learn how to set up and run in the Amazon Code Examples Repository.

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
  • For API details, see PutBucketCors in Amazon SDK for Python (Boto3) API Reference.

Ruby
SDK for Ruby
Note

There's more on GitHub. Find the complete example and learn how to set up and run in the Amazon Code Examples Repository.

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
  • For API details, see PutBucketCors in Amazon SDK for Ruby API Reference.

For a complete list of Amazon SDK developer guides and code examples, see Using this service with an Amazon SDK. This topic also includes information about getting started and details about previous SDK versions.