Get Bucket CORS Settings
Using this set of codes, you can get your bucket CORS settings.
Components
- Credentials
- Bucket Name
- .NET
- PHP
- Python
- Javascript
- GO
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX - License - Identifier: Apache - 2.0
namespace GetBucketCors
{
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Amazon;
using Amazon.S3;
using Amazon.S3.Model;
/// <summary>
/// This example show how to get cors configurations. This example was
/// created using the AWS SDK for .NET 3.7 and .NET Core 5.0.
/// </summary>
public class GetBucketCors
{
// 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);
await RetrieveCORSConfigurationAsync(_s3Client);
}
/// <summary>
///
/// </summary>
/// <param name="client"></param>
/// <returns></returns>
private static async Task<CORSConfiguration> RetrieveCORSConfigurationAsync(AmazonS3Client client)
{
GetCORSConfigurationRequest request = new ()
{
BucketName = BucketName,
};
var response = await client.GetCORSConfigurationAsync(request);
var configuration = response.Configuration;
PrintCORSRules(configuration);
return configuration;
}
/// <summary>
///
/// </summary>
/// <param name="configuration"></param>
private static void PrintCORSRules(CORSConfiguration configuration)
{
Console.WriteLine();
if (configuration is null)
{
Console.WriteLine("\nConfiguration is null");
return;
}
Console.WriteLine($"Configuration has {configuration.Rules.Count} rules:");
foreach (CORSRule rule in configuration.Rules)
{
Console.WriteLine($"Rule ID: {rule.Id}");
Console.WriteLine($"MaxAgeSeconds: {rule.MaxAgeSeconds}");
Console.WriteLine($"AllowedMethod: {string.Join(", ", rule.AllowedMethods.ToArray())}");
Console.WriteLine($"AllowedOrigins: {string.Join(", ", rule.AllowedOrigins.ToArray())}");
Console.WriteLine($"AllowedHeaders: {string.Join(", ", rule.AllowedHeaders.ToArray())}");
Console.WriteLine($"ExposeHeader: {string.Join(", ", rule.ExposeHeaders.ToArray())}");
}
}
}
}
<?php
require('client.php');
$bucket = $config['sample_bucket'];
try {
$result = $client->getBucketCors([
'Bucket' => $bucket, // REQUIRED
]);
var_dump($result);
} catch (AwsException $e) {
// Display error message
echo $e->getMessage();
echo "\n";
}
import boto3
import logging
from botocore.exceptions import ClientError
# Configure logging
logging.basicConfig(level=logging.INFO)
try:
# S3 resource
s3_resource = boto3.client(
's3',
endpoint_url='endpoint_url',
aws_access_key_id='access_key',
aws_secret_access_key='secret_key'
)
except Exception as exc:
logging.error(exc)
else:
try:
bucket_name = 'bucket_name'
response = s3_client.get_bucket_cors(Bucket=bucket_name)
logging.info(response['CORSRules'])
except ClientError as e:
if e.response['Error']['Code'] == 'NoSuchCORSConfiguration':
return []
else:
# AllAccessDisabled error == bucket not found
logging.error(e)
// Import required AWS SDK clients and commands for Node.js
const { S3Client, GetBucketCorsCommand } = require('@aws-sdk/client-s3');
// Create an S3 client service object
const s3 = new S3Client({
region: 'default',
endpoint: 'endpoint_url',
credentials: {
accessKeyId: 'access_key',
secretAccessKey: 'secret_key',
},
});
const run = async () => {
try {
const response = await s3.send(
new GetBucketCorsCommand({
Bucket: 'sample_bucket',
})
);
console.log('Success', response.CORSRules);
} catch (err) {
console.log('Error', err);
}
};
run();
package main
// snippet-start:[s3.go.set_cors.imports]
import (
"fmt"
"os"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/awserr"
"github.com/aws/aws-sdk-go/aws/credentials"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/s3"
)
// Lists CORS configuration
//
// Usage:
// go run s3_get_bucket_cors.go BUCKET_NAME
func main() {
if len(os.Args) != 2 {
exitErrorf("Bucket name required\nUsage: go run", os.Args[0], "BUCKET")
}
bucket := os.Args[1]
sess, err := session.NewSession(&aws.Config{
Credentials: credentials.NewStaticCredentials("<ACCESS_KEY>", "<SECRET_KEY>", ""),
})
svc := s3.New(sess, &aws.Config{
Region: aws.String("default"),
Endpoint: aws.String("<ENDPOINT_URL>"),
})
input := &s3.GetBucketCorsInput{
Bucket: aws.String(bucket),
}
result, err := svc.GetBucketCors(input)
if err != nil {
if aerr, ok := err.(awserr.Error); ok {
switch aerr.Code() {
default:
fmt.Println(aerr.Error())
}
} else {
// Print the error, cast err to awserr.Error to get the Code and
// Message from an error.
fmt.Println(err.Error())
}
return
}
fmt.Println(result)
}
// snippet-start:[s3.go.set_cors.exit]
func exitErrorf(msg string, args ...interface{}) {
fmt.Fprintf(os.Stderr, msg+"\n", args...)
os.Exit(1)
}
The following command can be used to execute the aforementioned code, presuming the code file is called s3_get_bucket_cors.go:
go run s3_get_bucket_cors.go BUCKET