All Products
Search
Document Center

Object Storage Service:Cross-origin resource sharing (CORS)

Last Updated:Feb 27, 2025

Due to the same-origin policy of browsers, cross-origin requests may be rejected when data is exchanged or resources are shared between different domain names. This topic describes how to resolve related issues by configuring cross-origin resource sharing (CORS) rules, in which you can specify the domain names from which requests can be sent, the methods that can be used to send cross-origin requests, and the allowed headers.

Usage notes

  • The sample code in this topic uses the region ID cn-hangzhou of the China (Hangzhou) region. By default, the public endpoint is used to access resources in a bucket. If you want to access resources in the bucket by using other Alibaba Cloud services in the same region in which the bucket is located, use an internal endpoint. For more information about the regions and endpoints supported by OSS, see OSS regions and endpoints.

  • In this topic, access credentials are obtained from environment variables. For more information about how to configure access credentials, see Configure access credentials.

  • To configure CORS rules, you must have the oss:PutBucketCors permission. To query CORS rules, you must have the oss:GetBucketCors permission. To delete CORS rules, you must have the oss:DeleteBucketCors permission. For more information, see Grant custom policy to RAM users.

Sample code

Configure CORS rules

The following sample code provides an example of how to configure CORS rules for a specific bucket.

package main

import (
	"context"
	"flag"
	"log"

	"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss"
	"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss/credentials"
)

// Define global variables.
var (
	region     string // Region in which your bucket is located.
	bucketName string // Name of the bucket.
)

// Specify the init function used to initialize command line parameters.
func init() {
	flag.StringVar(&region, "region", "", "The region in which the bucket is located.")
	flag.StringVar(&bucketName, "bucket", "", "The name of the bucket.")
}

func main() {
	// Parse command line parameters.
	flag.Parse()

	// Check whether the name of the bucket is specified.
	if len(bucketName) == 0 {
		flag.PrintDefaults()
		log.Fatalf("invalid parameters, bucket name required")
	}

	// Check whether the region is specified.
	if len(region) == 0 {
		flag.PrintDefaults()
		log.Fatalf("invalid parameters, region required")
	}

	// Load the default configurations and specify the credential provider and region.
	cfg := oss.LoadDefaultConfig().
		WithCredentialsProvider(credentials.NewEnvironmentVariableCredentialsProvider()).
		WithRegion(region)

	// Create an OSS client.
	client := oss.NewClient(cfg)

	// Create a request to configure the CORS rules for the bucket.
	request := &oss.PutBucketCorsRequest{
		Bucket: oss.Ptr(bucketName), // Name of the bucket.
		CORSConfiguration: &oss.CORSConfiguration{
			CORSRules: []oss.CORSRule{
				{
					AllowedOrigins: []string{"*"},             // Allow requests from all origins.
					AllowedMethods: []string{"PUT", "GET"},    // Allowed methods.
					AllowedHeaders: []string{"Authorization"}, // Allowed request headers.
				},
				{
					AllowedOrigins: []string{"http://example.com", "http://example.net"}, // Allow requests from specified origins.
					AllowedMethods: []string{"GET"},                                      // Allowed methods.
					AllowedHeaders: []string{"Authorization"},                            // Allowed request headers.
					ExposeHeaders:  []string{"x-oss-test", "x-oss-test1"},                // Exposed response headers.
					MaxAgeSeconds:  oss.Ptr(int64(100)),                                  // Maximum cache time. Unit: seconds.
				},
			},
			ResponseVary: oss.Ptr(false), // Whether to include the Vary header in the response.
		},
	}

	// Send the request to configure the CORS rules for the bucket.
	result, err := client.PutBucketCors(context.TODO(), request)
	if err != nil {
		log.Fatalf("failed to put bucket cors %v", err)
	}

	// Display the result.
	log.Printf("put bucket cors result:%#v\n", result)
}

Query CORS rules

The following sample code provides an example of how to query CORS rules.

package main

import (
	"context"
	"flag"
	"log"

	"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss"
	"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss/credentials"
)

// Define global variables.
var (
	region     string // Region in which your bucket is located.
	bucketName string // Name of the bucket.
)

// Specify the init function used to initialize command line parameters.
func init() {
	flag.StringVar(&region, "region", "", "The region in which the bucket is located.")
	flag.StringVar(&bucketName, "bucket", "", "The name of the bucket.")
}

func main() {
	// Parse command line parameters.
	flag.Parse()

	// Check whether the name of the bucket is specified.
	if len(bucketName) == 0 {
		flag.PrintDefaults()
		log.Fatalf("invalid parameters, bucket name required")
	}

	// Check whether the region is specified.
	if len(region) == 0 {
		flag.PrintDefaults()
		log.Fatalf("invalid parameters, region required")
	}

	// Load the default configurations and specify the credential provider and region.
	cfg := oss.LoadDefaultConfig().
		WithCredentialsProvider(credentials.NewEnvironmentVariableCredentialsProvider()).
		WithRegion(region)

	// Create an OSS client.
	client := oss.NewClient(cfg)

	// Create a request to query the CORS configurations of the bucket.
	request := &oss.GetBucketCorsRequest{
		Bucket: oss.Ptr(bucketName), // Name of the bucket.
	}

	// Perform the query operation and process the result.
	getResult, err := client.GetBucketCors(context.TODO(), request)
	if err != nil {
		log.Fatalf("failed to get bucket cors %v", err)
	}

	// Display the result.
	log.Printf("get bucket cors result:%#v\n", getResult.CORSConfiguration.CORSRules)
}

Delete CORS rules

The following sample code provides an example of how to delete all CORS rules configured for a specific bucket.

package main

import (
	"context"
	"flag"
	"log"

	"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss"
	"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss/credentials"
)

// Define global variables.
var (
	region     string // Region in which your bucket is located.
	bucketName string // Name of the bucket.
)

// Specify the init function used to initialize command line parameters.
func init() {
	flag.StringVar(&region, "region", "", "The region in which the bucket is located.")
	flag.StringVar(&bucketName, "bucket", "", "The name of the bucket.")
}

func main() {
	// Parse command line parameters.
	flag.Parse()

	// Check whether the name of the bucket is specified.
	if len(bucketName) == 0 {
		flag.PrintDefaults()
		log.Fatalf("invalid parameters, bucket name required")
	}

	// Check whether the region is specified.
	if len(region) == 0 {
		flag.PrintDefaults()
		log.Fatalf("invalid parameters, region required")
	}

	// Load the default configurations and specify the credential provider and region.
	cfg := oss.LoadDefaultConfig().
		WithCredentialsProvider(credentials.NewEnvironmentVariableCredentialsProvider()).
		WithRegion(region)

	// Create an OSS client.
	client := oss.NewClient(cfg)

	// Create a request to delete the CORS configurations.
	request := &oss.DeleteBucketCorsRequest{
		Bucket: oss.Ptr(bucketName), // Name of the bucket.
	}

	// Delete the CORS configurations and process the result.
	result, err := client.DeleteBucketCors(context.TODO(), request)
	if err != nil {
		log.Fatalf("failed to delete bucket cors %v", err)
	}

	// Display the result.
	log.Printf("delete bucket cors result:%#v\n", result)
}

References