تعیین تنظیمات CORS روی صندوقچه
با استفاده از این امکان شما میتوانید تنظیمات CORS مربوط به صندوقچهی خود را تعیین کنید.
مولفهها
- کلیدهای احراز هویت
- نام صندوقچه
- قوانین CORS
قوانین CORS
شما میتوانید مجموعه قوانین CORS را در یک لیست تعریف کنید. هر یک از این قوانین میتوانند شامل کلیدهای زیر باشند:
- AllowedHeaders
- AllowedMethods (اجباری)
- AllowedOrigins (اجباری)
- ExposeHeaders
- MaxAgeSeconds
برای آشنایی با شیوهی اجرای این قوانین میتوانید به مستندات مربوط به تعیین تنظیمات CORS مراجعه کنید.
- NET.
- PHP
- Python
- Javascript
- GO
// 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());
}
}
}
}
<?php
require('client.php');
$bucket = $config['sample_bucket'];
try {
$result = $client->putBucketCors([
'Bucket' => $bucket, // REQUIRED
'CORSConfiguration' => [ // REQUIRED
'CORSRules' => [ // REQUIRED
'AllowedHeaders' => ['Authorization', 'custom-header'],
'AllowedMethods' => ['POST', 'GET', 'PUT'], // REQUIRED
'AllowedOrigins' => ['sample-domain2.arvan'], // REQUIRED
'ExposeHeaders' => [],
'ID' => 'MY_CORS_CONFIG_ID',
'MaxAgeSeconds' => 3000,
],
// ...
],
],
]);
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'
cors_configuration = {
'CORSRules': [{
'AllowedHeaders': ['Authorization', 'x-custom-header'],
'AllowedMethods': ['GET', 'PUT'],
'AllowedOrigins': ['sampledomain.arvan'],
'ExposeHeaders': ['GET', 'PUT'],
'MaxAgeSeconds': 3000
}]
}
response = s3_client.put_bucket_cors(
Bucket=bucket,
CORSConfiguration=cors_configuration
)
logging.info(response)
except ClientError as e:
logging.error(e)
// Import required AWS SDK clients and commands for Node.js
const { S3Client, PutBucketCorsCommand } = 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 cors = {
Bucket: 'sample_bucket', // REQUIRED
CORSConfiguration: {
// REQUIRED
CORSRules: [
// REQUIRED
{
AllowedHeaders: ['Authorization', 'custom-header'],
AllowedMethods: ['POST', 'GET', 'PUT'], // REQUIRED
AllowedOrigins: ['sample-domain2.arvan'], // REQUIRED
ExposeHeaders: [],
MaxAgeSeconds: 3000,
},
],
},
};
const run = async () => {
try {
const response = await s3.send(new PutBucketCorsCommand(cors));
console.log('Success', response);
} catch (err) {
console.log('Error', err);
}
};
run();
package main
// snippet-start:[s3.go.set_cors.imports]
import (
"flag"
"fmt"
"os"
"strings"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/credentials"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/s3"
)
// snippet-end:[s3.go.set_cors.imports]
// Configures CORS rules for a bucket by setting the allowed
// HTTP methods.
//
// Requires the bucket name, and can also take a space separated
// list of HTTP methods.
//
// Usage:
// go run s3_put_bucket_cors.go -b BUCKET_NAME get put
func main() {
// snippet-start:[s3.go.set_cors.vars]
bucketPtr := flag.String("b", "", "Bucket to set CORS on, (required)")
flag.Parse()
if *bucketPtr == "" {
exitErrorf("-b <bucket> Bucket name required")
}
methods := filterMethods(flag.Args())
// snippet-end:[s3.go.set_cors.vars]
// Initialize a session
// snippet-start:[s3.go.set_cors.session]
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>"),
})
// snippet-end:[s3.go.set_cors.session]
// Create a CORS rule for the bucket
// snippet-start:[s3.go.set_cors.rule]
rule := s3.CORSRule{
AllowedHeaders: aws.StringSlice([]string{"Authorization"}),
AllowedOrigins: aws.StringSlice([]string{"*"}),
MaxAgeSeconds: aws.Int64(3000),
// Add HTTP methods CORS request that were specified in the CLI.
AllowedMethods: aws.StringSlice(methods),
}
// snippet-end:[s3.go.set_cors.rule]
// Create the parameters for the PutBucketCors API call, add add
// the rule created to it.
// snippet-start:[s3.go.set_cors.put]
params := s3.PutBucketCorsInput{
Bucket: bucketPtr,
CORSConfiguration: &s3.CORSConfiguration{
CORSRules: []*s3.CORSRule{&rule},
},
}
_, err = svc.PutBucketCors(¶ms)
if err != nil {
// Print the error message
exitErrorf("Unable to set Bucket %q's CORS, %v", *bucketPtr, err)
}
// Print the updated CORS config for the bucket
fmt.Printf("Updated bucket %q CORS for %v\n", *bucketPtr, methods)
// snippet-end:[s3.go.set_cors.put]
}
// snippet-start:[s3.go.set_cors.exit]
func exitErrorf(msg string, args ...interface{}) {
fmt.Fprintf(os.Stderr, msg+"\n", args...)
os.Exit(1)
}
// snippet-end:[s3.go.set_cors.exit]
// snippet-start:[s3.go.set_cors.filter]
func filterMethods(methods []string) []string {
filtered := make([]string, 0, len(methods))
for _, m := range methods {
v := strings.ToUpper(m)
switch v {
case "POST", "GET", "PUT", "PATCH", "DELETE":
filtered = append(filtered, v)
}
}
return filtered
}
برای اجرای قطعه کد بالا با فرض نامگذاری فایل کد به s3_put_bucket_cors.go میتوان از دستور زیر استفاده کرد:
go run s3_put_bucket_cors.go -b BUCKET_NAME get put