Skip to main content

Configure CORS on Bucket

Using this feature you can configure CORS on your bucket.

Components

CORS Policies

You can define a set of CORS policies as a list. Each of these policies can include the following keys:

  • AllowedHeaders
  • AllowedMethods (Mandatory)
  • AllowedOrigins (Mandatory)
  • ExposeHeaders
  • MaxAgeSeconds

For more information on how to enforce these policies, you can refer to the Managing CORS Settings documentation.

// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX - License - Identifier: Apache - 2.0

namespace PutBucketCors
{
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Amazon;
using Amazon.S3;
using Amazon.S3.Model;
using System.Reflection;

/// <summary>
/// This example shows how to configure your bucket to allow cross-origin
/// requests by creating a CORS configuration. This example was
/// created using the AWS SDK for .NET 3.7 and .NET Core 5.0.
/// </summary>
public class PutBucketCors
{
// Remember to change the bucket name to the name of an Amazon Simple
// Storage Service (Amazon S3) bucket that exists on your account.
private const string BucketName = "<BUCKET_NAME>";

/// <summary>
/// The Main method creates the the bucket to be able to accept CORS
/// requests.
/// </summary>
public static async Task Main()
{
var awsCredentials = new Amazon.Runtime.BasicAWSCredentials("<ACCESS-KEY>", "<SECRET-KEY>");
var config = new AmazonS3Config { ServiceURL = "<ENDPOINT>" };
var _s3Client = new AmazonS3Client(awsCredentials, config);

CORSConfiguration configuration = new ()
{
Rules = new List<CORSRule>
{
new CORSRule
{
Id = "CORSRule1",
AllowedMethods = new List<string> { "GET", "PUT", "POST", "DELETE" },
AllowedOrigins = new List<string> { "*" },
MaxAgeSeconds = 3000,
AllowedHeaders = new List<string> { "Authorization" },
},
},
};

await PutCORSConfigurationAsync(_s3Client, configuration);
}

/// <summary>
///
/// </summary>
/// <param name="client"></param>
/// <param name="configuration"></param>
/// <returns></returns>
private static async Task PutCORSConfigurationAsync(AmazonS3Client client, CORSConfiguration configuration)
{
try
{
PutCORSConfigurationRequest request = new ()
{
BucketName = BucketName,
Configuration = configuration,
};

PutCORSConfigurationResponse response = await client.PutCORSConfigurationAsync(request);

Console.WriteLine($"CORS configurations set on {BucketName} bucket");
}
catch (AmazonS3Exception amazonS3Exception)
{
Console.WriteLine("An AmazonS3Exception was thrown. Exception: " + amazonS3Exception.ToString());
}
catch (Exception e)
{
Console.WriteLine("Exception: " + e.ToString());
}
}
}
}