All Products
Search
Document Center

Object Storage Service:CORS

Last Updated:Nov 06, 2024

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. To resolve the issue, you can configure cross-origin resource sharing (CORS) rules. In the CORS rules, 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

  • In this topic, the public endpoint of the China (Hangzhou) region is used. If you want to access OSS from other Alibaba Cloud services in the same region as OSS, use an internal endpoint. For more information about OSS regions and endpoints, see Regions, endpoints and open ports.

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

  • In this topic, an OSSClient instance is created by using an OSS endpoint. If you want to create an OSSClient instance by using custom domain names or Security Token Service (STS), see Initialization.

  • 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 Attach a custom policy to a RAM user.

Sample Code

Configure CORS rules

The following sample code provides an example on how to configure a CORS rule for a specific bucket:

package main

import (
	"log"

	"github.com/aliyun/aliyun-oss-go-sdk/oss"
)

func main() {
	// Specify the name of the bucket. 
	bucketName := "yourBucketName"

	// Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured.
	provider, err := oss.NewEnvironmentVariableCredentialsProvider()
	if err != nil {
		log.Fatalf("Error creating credentials provider: %v", err)
	}

	// Create an OSSClient instance. 
	// Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. Specify your actual endpoint. 
	// Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou. Specify the actual region.
	clientOptions := []oss.ClientOption{oss.SetCredentialsProvider(&provider)}
	clientOptions = append(clientOptions, oss.Region("yourRegion"))
	// Specify the version of the signature algorithm.
	clientOptions = append(clientOptions, oss.AuthVersion(oss.AuthV4))
	client, err := oss.New("yourEndpoint", "", "", clientOptions...)
	if err != nil {
		log.Fatalf("Error creating OSS client: %v", err)
	}

	isTrue := true
	rule1 := oss.CORSRule{
		AllowedOrigin: []string{"*"},
		AllowedMethod: []string{"PUT", "GET", "POST"},
		AllowedHeader: []string{},
		ExposeHeader:  []string{},
		MaxAgeSeconds: 100,
	}

	rule2 := oss.CORSRule{
		AllowedOrigin: []string{"http://www.a.com", "http://www.b.com"},
		AllowedMethod: []string{"GET"},
		AllowedHeader: []string{"Authorization"},
		ExposeHeader:  []string{"x-oss-test-01", "x-oss-test-02"},
		MaxAgeSeconds: 100,
	}

	put := oss.PutBucketCORS{}
	put.CORSRules = []oss.CORSRule{rule1, rule2}
	put.ResponseVary = &isTrue

	// Create the CORS rules. 
	err = client.SetBucketCORSV2(bucketName, put)
	if err != nil {
		log.Fatalf("Error setting CORS rules: %v", err)
	}

	log.Println("Set Success")
}

Query CORS rules

The following sample code provides an example on how to query CORS rules of a specific bucket:

package main

import (
	"log"

	"github.com/aliyun/aliyun-oss-go-sdk/oss"
)

func main() {
	// Specify the name of the bucket. 
	bucketName := "yourBucketName"

	// Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured. 
	provider, err := oss.NewEnvironmentVariableCredentialsProvider()
	if err != nil {
		log.Fatalf("Error creating credentials provider: %v", err)
	}

	// Create an OSSClient instance. 
	// Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. Specify your actual endpoint. 
	// Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou. Specify the actual region.
	clientOptions := []oss.ClientOption{oss.SetCredentialsProvider(&provider)}
	clientOptions = append(clientOptions, oss.Region("yourRegion"))
	// Specify the version of the signature algorithm.
	clientOptions = append(clientOptions, oss.AuthVersion(oss.AuthV4))
	client, err := oss.New("yourEndpoint", "", "", clientOptions...)
	if err != nil {
		log.Fatalf("Error creating OSS client: %v", err)
	}

	// Query the CORS rules. 
	corsRes, err := client.GetBucketCORS(bucketName)
	if err != nil {
		log.Fatalf("Error getting CORS rules: %v", err)
	}

	// Display the CORS rules.
	for _, rule := range corsRes.CORSRules {
		log.Printf("Cors Rules Allowed Origin: %v", rule.AllowedOrigin)
		log.Printf("Cors Rules Allowed Method: %v", rule.AllowedMethod)
		log.Printf("Cors Rules Allowed Header: %v", rule.AllowedHeader)
		log.Printf("Cors Rules Expose Header: %v", rule.ExposeHeader)
		log.Printf("Cors Rules Max Age Seconds: %d", rule.MaxAgeSeconds)
	}

	if corsRes.ResponseVary != nil {
		log.Printf("Cors Rules Response Vary: %t", *corsRes.ResponseVary)
	}
}

Delete CORS rules

The following sample code provides an example on how to delete all CORS rules of a specific bucket:

package main

import (
	"log"

	"github.com/aliyun/aliyun-oss-go-sdk/oss"
)

func main() {
	// Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured. 
	provider, err := oss.NewEnvironmentVariableCredentialsProvider()
	if err != nil {
		log.Fatalf("Error creating credentials provider: %v", err)
	}

	// Create an OSSClient instance. 
	// Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. Specify your actual endpoint. 
	// Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou. Specify the actual region.
	clientOptions := []oss.ClientOption{oss.SetCredentialsProvider(&provider)}
	clientOptions = append(clientOptions, oss.Region("yourRegion"))
	// Specify the version of the signature algorithm.
	clientOptions = append(clientOptions, oss.AuthVersion(oss.AuthV4))
	client, err := oss.New("yourEndpoint", "", "", clientOptions...)
	if err != nil {
		log.Fatalf("Error creating OSS client: %v", err)
	}

	// Specify the name of the bucket. Example: examplebucket. 
	bucketName := "examplebucket"

	// Delete the CORS rules. 
	err = client.DeleteBucketCORS(bucketName)
	if err != nil {
		log.Fatalf("Error deleting CORS rules: %v", err)
	}

	log.Println("Delete Bucket CORS Success")
}

References

  • For the complete sample code that is used to manage CORS rules, visit GitHub.

  • For more information about the API operation that you can call to configure CORS rules, see SetBucketCORSV2.

  • For more information about the API operation that you can call to query CORS rules, see GetBucketCORS.

  • For more information about the API operation that you can call to delete CORS rules, see DeleteBucketCORS.