All Products
Search
Document Center

Object Storage Service:Configure CORS in OSS

Last Updated:Jan 29, 2024

Browsers enforce the same-origin policy, which allows JavaScript code executed on a web page to access resources only from the same origin and denies cross-origin requests. Cross-origin resource sharing (CORS) allows web browsers to initiate requests from a domain or an origin to a different domain or origin. CORS allows JavaScript code loaded on your websites to successfully request objects on an Object Storage Service (OSS) server that has a different origin.

Same-origin policy

Browsers reject cross-origin requests based on the same-origin policy to keep website content secure. For example, if the JavaScript code on one website makes a request for a resource hosted on another website that has a different origin, the browser denies the request.

Two URLs have the same origin if they have the same protocol, domain name or IP address, and port number (if specified). The following table provides examples of origin comparison with http://www.aliyun.com/org/test.html.

URL

Successful access

Reason

http://www.aliyun.com/org/other.html

Yes

Same protocol, domain name, and port number

http://www.aliyun.com/org/internal/page.html

Yes

Same protocol, domain name, and port number

https://www.aliyun.com/page.html

No

Different protocols (HTTP and HTTPS)

http://www.aliyun.com:22/dir/page.html

No

Different port numbers (22 and no port number)

http://www.alibabacloud.com/help/other.html

No

Different domain names

The preceding table shows that the browser rejects requests from a URL to another URL that has a different origin. If you want to allow cross-origin requests, you must configure CORS rules.

Usage notes

  • You can configure up to 10 CORS rules for a bucket.

  • When Object Storage Service (OSS) receives a cross-origin request or an OPTIONS request that is destined for a bucket, OSS reads the CORS rules that are configured for the bucket and attempts to match the rules one after another. If OSS finds the first match, OSS returns corresponding headers. If the request fails to match the CORS rules, OSS does not include CORS headers in the response.

  • To implement CORS after Alibaba Cloud CDN is activated, you must configure CORS rules in the CDN console. For more information, see Alibaba Cloud Content Delivery Network how to configure cross-origin resource sharing by using HTTP headers (CORS).

CORS rules

You can configure CORS rules to allow or reject cross-origin requests based on your requirements. CORS rules are configured only to determine whether to add CORS-related headers to requests. The browser determines whether to reject cross-origin requests.

If one of the following conditions is met, you need to select Vary: Origin to avoid local cache errors.

Important

If Vary: Origin is selected, visits from the browser or the CDN back-to-origin requests may increase.

  • CORS and non-CORS requests are sent at the same time

    The following sample code provides an example of a non-CORS request that is created in the <img> field and a CORS request that is created by using the fetch method:

    <!doctype html>
    <html>
    <head>
     <meta charset="UTF-8">
     <title>CORS Test</title>
    </head>
    <body>
    <! -- Non-CORS request -->
    <img src="https://examplebucket.oss-cn-beijing.aliyuncs.com/exampleobject.txt" alt="">
    <script>
      <! -- CORS request -->
     fetch("https://examplebucket.oss-cn-beijing.aliyuncs.com/exampleobject.txt").then(console.log)
    </script>
    </body>
    </html>
  • The Origin header has multiple possible values

    For example, you set the Origin header to http://www.example.com and https://www.example.org to allow CORS requests from these origins.

Procedure

Use the OSS console

  1. Log on to the OSS console.

  2. In the left-side navigation pane, click Buckets. On the Buckets page, find and click the desired bucket.

  3. In the left-side navigation tree, choose Content Security > CORS.

  4. On the CORS page, click Create Rule.

  5. In the Create Rule panel, configure the parameters. The following table describes the parameters.

    Parameter

    Required

    Description

    Source

    Yes

    The origins from which cross-origin requests are allowed. When you configure this parameter, take note of the following items:

    • You can specify multiple allowed origins. Separate multiple origins with line feeds.

    • An origin URL must include the protocol, such as HTTP or HTTPS.

    • You can use an asterisk (*) as the wildcard character in an origin URL. Each origin can contain up to one asterisk (*).

    • If an origin URL does not use the default port number, specify the actual port number. Example: https://www.example.com:8080.

    The following examples show how to configure allowed origins:

    • To allow requests from a specific origin, specify the origin URL. Example: https://www.example.com.

    • To allow requests from subdomains of a specific root domain, use an asterisk (*) wildcard character in an origin URL. Example: https://*.example.com.

    • To allow requests from all origins, enter only an asterisk (*) wildcard character.

    Allowed Methods

    Yes

    The methods that cross-origin requests are allowed to use.

    Allowed Headers

    No

    The allowed headers in cross-origin requests. When you configure the headers, take note of the following items:

    • The value of this parameter is in the key:value format and not case-sensitive. Example: content-type:text/plain.

    • You can configure multiple headers. Separate multiple headers with line feeds.

    • You can use an asterisk (*) as the wildcard character. Each header can contain up to one asterisk (*). Set this parameter to an asterisk (*) if you do not have special requirements.

    Exposed Headers

    No

    The response headers available to requests from applications, such as an XMLHttpRequest object in JavaScript. Exposed headers cannot contain an asterisk (*) wildcard character.

    We recommend that you configure the following common exposed headers:

    • x-oss-request-id

      If an issue occurs, provide technical support with the request ID for troubleshooting.

    • ETag

      You can use the ETag value of an object to check whether the object content is modified.

    Cache Timeout (Seconds)

    No

    The period of time in which the browser can cache the response to an OPTIONS preflight request for specific resources. Unit: seconds.

    Vary: Origin

    No

    Specifies whether to return the Vary: Origin header.

    If both CORS and non-CORS requests are sent to OSS, or if the Origin header has multiple possible values, we recommend that you select Vary: Origin to prevent errors in the local cache.

    Important

    If Vary: Origin is selected, visits from the browser or the CDN back-to-origin requests may increase.

  6. Click OK.

Use OSS SDKs

The following code provides examples on how to configure CORS rules by using OSS SDKs for common programming languages. For more information about how to configure CORS rules by using OSS SDKs for other programming languages, see Overview.

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.common.auth.*;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.SetBucketCORSRequest;
import java.util.ArrayList;

public class Demo {

    public static void main(String[] args) throws Exception {
        // In this example, the endpoint of the China (Hangzhou) region is used. Specify your actual endpoint. 
        String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
        // 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. 
        EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
        // Specify the name of the bucket. Example: examplebucket. 
        String bucketName = "examplebucket";

        // Create an OSSClient instance. 
        OSS ossClient = new OSSClientBuilder().build(endpoint, credentialsProvider);

        try {
            SetBucketCORSRequest request = new SetBucketCORSRequest(bucketName);

            // You can configure up to 10 CORS rules for a bucket. 
            ArrayList<SetBucketCORSRequest.CORSRule> putCorsRules = new ArrayList<SetBucketCORSRequest.CORSRule>();

            SetBucketCORSRequest.CORSRule corRule = new SetBucketCORSRequest.CORSRule();

            ArrayList<String> allowedOrigin = new ArrayList<String>();
            // Specify the origins from which cross-origin requests are allowed. 
            allowedOrigin.add( "http://example.com");

            ArrayList<String> allowedMethod = new ArrayList<String>();
            // Specify the methods that can be used to send cross-origin requests, including GET, PUT, DELETE, POST, and HEAD. 
            allowedMethod.add("GET");

            ArrayList<String> allowedHeader = new ArrayList<String>();
            // Specify whether the headers that are specified by Access-Control-Request-Headers in the OPTIONS preflight request are allowed. 
            allowedHeader.add("x-oss-test");

            ArrayList<String> exposedHeader = new ArrayList<String>();
            // Specify the response headers for allowed access requests from applications. 
            exposedHeader.add("x-oss-test1");
            // You can use only one asterisk (*) as a wildcard character for AllowedOrigins and AllowedMethods in a CORS rule. The asterisk (*) wildcard character specifies that all origins or operations are allowed. 
            corRule.setAllowedMethods(allowedMethod);
            corRule.setAllowedOrigins(allowedOrigin);
            // AllowedHeaders and ExposeHeaders do not support wildcard characters. 
            corRule.setAllowedHeaders(allowedHeader);
            corRule.setExposeHeaders(exposedHeader);
            // Specify the period of time in which the browser can cache the response for an OPTIONS preflight request for specific resources. Unit: seconds. 
            corRule.setMaxAgeSeconds(10);

            // You can configure up to 10 CORS rules for the bucket. 
            putCorsRules.add(corRule);
            // The existing CORS rules are overwritten. 
            request.setCorsRules(putCorsRules);
            // Specify whether to return the "Vary: Origin" header. If you set this parameter to TRUE, the Vary: Origin header is returned regardless of whether the request is a cross-origin request or whether the cross-origin request is successful. If you set this parameter to False, the Vary: Origin header is not returned. 
            // request.setResponseVary(Boolean.TRUE);
            ossClient.setBucketCORS(request);
        } catch (OSSException oe) {
            System.out.println("Caught an OSSException, which means your request made it to OSS, "
                    + "but was rejected with an error response for some reason.");
            System.out.println("Error Message:" + oe.getErrorMessage());
            System.out.println("Error Code:" + oe.getErrorCode());
            System.out.println("Request ID:" + oe.getRequestId());
            System.out.println("Host ID:" + oe.getHostId());
        } catch (ClientException ce) {
            System.out.println("Caught an ClientException, which means the client encountered "
                    + "a serious internal problem while trying to communicate with OSS, "
                    + "such as not being able to access the network.");
            System.out.println("Error Message:" + ce.getMessage());
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }
}
<?php
if (is_file(__DIR__ . '/../autoload.php')) {
    require_once __DIR__ . '/../autoload.php';
}
if (is_file(__DIR__ . '/../vendor/autoload.php')) {
    require_once __DIR__ . '/../vendor/autoload.php';
}

use OSS\OssClient;
use OSS\Core\OssException;
use OSS\Model\CorsConfig;
use OSS\Model\CorsRule;

// 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. 
$accessKeyId = getenv("OSS_ACCESS_KEY_ID");
$accessKeySecret = getenv("OSS_ACCESS_KEY_SECRET");
// 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. 
$endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
// Specify the name of the bucket. Example: examplebucket. 
$bucket= "examplebucket";

$corsConfig = new CorsConfig();
$rule = new CorsRule();
// Specify the response headers based on which to allow cross-origin requests. You can specify multiple allowed headers. Only one asterisk (*) can be used as the wildcard character for each allowed header. 
// If you do not have special requirements, we recommend that you set AllowedHeader to an asterisk (*). 
$rule->addAllowedHeader("*");
// Specify the response headers that you are allowed to access from applications. You can specify multiple exposed headers. Exposed headers cannot contain asterisks (*). 
$rule->addExposeHeader("x-oss-header");
// Specify the allowed origins from which cross-origin requests are sent. You can specify multiple allowed origins. Only one asterisk (*) can be used as the wildcard character for each allowed origin. 
$rule->addAllowedOrigin("https://example.com:8080");
$rule->addAllowedOrigin("https://*.aliyun.com");
// If you set AllowedOrigin to an asterisk (*), requests from all origins are allowed. 
//$rule->addAllowedOrigin("*");
// Specify the HTTP methods that cross-origin requests are allowed to use. 
$rule->addAllowedMethod("POST");
// Specify the time that the browser can cache the response to a preflight (OPTIONS) request to a specific resource. Unit: seconds. 
$rule->setMaxAgeSeconds(10);
// You can add up to 10 rules for each bucket. 
$corsConfig->addRule($rule);

try{
    $ossClient = new OssClient($accessKeyId, $accessKeySecret, $endpoint);

    // OSS overwrites an existing CORS rule that has the same name as the CORS rule that you want to create in the request. 
    $ossClient->putBucketCors($bucket, $corsConfig);
} catch(OssException $e) {
    printf(__FUNCTION__ . ": FAILED\n");
    printf($e->getMessage() . "\n");
    return;
}
print(__FUNCTION__ . ": OK" . "\n");            
const OSS = require('ali-oss');

const client = new OSS({
  // 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 oss-cn-hangzhou. 
  region: 'yourRegion',
  // Obtain access credentials from environment variables. Before you run the sample code, make sure that you have configured environment variables OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET. 
  accessKeyId: process.env.OSS_ACCESS_KEY_ID,
  accessKeySecret: process.env.OSS_ACCESS_KEY_SECRET,
  // Specify the name of the bucket. 
  bucket: 'yourBucket'
});

const rules = [{
        // Specify the origin of allowed cross-origin requests. You can set the origin to an asterisk (*) to allow requests from all regions. 
        allowedOrigin: 'http://example.com',
        // Specify the methods that can be used to send cross-origin requests, including GET, PUT, DELETE, POST, and HEAD. 
        allowedMethod: 'GET',
        // Specify the response headers that allow cross-origin requests. We recommend that you use an asterisk (*) as the value, unless otherwise specified. 
        allowedHeader: '*',
        // Specify the response headers for allowed access requests from applications, such as an XMLHttpRequest object in JavaScript. An asterisk (*) is not supported. 
        exposeHeader: 'Content-Length',
        // Specify the period of time in which the browser can cache the response to an OPTIONS preflight request for specific resources. Unit: seconds. 
        maxAgeSeconds: '30'
  },
];
// You can configure up to 10 CORS rules. If a new rule that is the same as an existing rule is configured, the existing rule is overwritten. 
client.putBucketCORS("yourBucket", rules).then((r) => {
  console.log(r);
});           
# -*- coding: utf-8 -*-
import oss2
from oss2.credentials import EnvironmentVariableCredentialsProvider
from oss2.models import BucketCors, CorsRule

# Obtain access credentials from the environment variables. Before you run the sample code, make sure that you have configured environment variables OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET. 
auth = oss2.ProviderAuth(EnvironmentVariableCredentialsProvider())
# 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 the name of the bucket. Example: examplebucket. 
bucket = oss2.Bucket(auth, 'https://oss-cn-hangzhou.aliyuncs.com', 'examplebucket')

rule = CorsRule(allowed_origins=['*'],
                allowed_methods=['GET', 'HEAD'],
                allowed_headers=['*'],
                max_age_seconds=1000)

# An existing rule with the same name is overwritten. 
bucket.put_bucket_cors(BucketCors([rule]))            
using Aliyun.OSS;
using Aliyun.OSS.Common;

// 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. 
var endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
// 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. 
var accessKeyId = Environment.GetEnvironmentVariable("OSS_ACCESS_KEY_ID");
var accessKeySecret = Environment.GetEnvironmentVariable("OSS_ACCESS_KEY_SECRET");
// Specify the name of the bucket. Example: examplebucket. 
var bucketName = "examplebucket";

// Create an OSSClient instance. 
var client = new OssClient(endpoint, accessKeyId, accessKeySecret);
try
{
    var request = new SetBucketCorsRequest(bucketName);
    var rule1 = new CORSRule();
    // Specify the origins from which cross-origin requests are allowed. 
    rule1.AddAllowedOrigin("http://example.com");
    // Specify the methods that can be used to send cross-origin requests, including GET, PUT, DELETE, POST, and HEAD. 
    rule1.AddAllowedMethod("POST");
    // AllowedHeaders and ExposeHeaders do not support wildcard characters. 
    rule1.AddAllowedHeader("*");
    // Specify the response headers for allowed access requests from applications. 
    rule1.AddExposeHeader("x-oss-test");
    // You can configure up to 10 CORS rules for a bucket. 
    request.AddCORSRule(rule1);
    var rule2 = new CORSRule();
    // You can use only one asterisk (*) as a wildcard character for AllowedOrigins and AllowedMethods in a CORS rule. The asterisk (*) wildcard character specifies that all origins or operations are allowed. 
    rule2.AddAllowedOrigin("http://example.net");
    rule2.AddAllowedMethod("GET");
    // Specify whether the headers that are specified by Access-Control-Request-Headers in the OPTIONS preflight request are allowed. 
    rule2.AddExposeHeader("x-oss-test2");
    // Specify the period of time in which the browser can cache the response for an OPTIONS preflight request for specific resources. Unit: seconds. 
    rule2.MaxAgeSeconds = 100;
    request.AddCORSRule(rule2);
    // Configure the CORS rules. 
    client.SetBucketCors(request);
    Console.WriteLine("Set bucket:{0} Cors succeeded ", bucketName);
}
catch (OssException ex)
{
    Console.WriteLine("Failed with error info: {0}; Error info: {1}. \nRequestID:{2}\tHostID:{3}",
        ex.ErrorCode, ex.Message, ex.RequestId, ex.HostId);
}
catch (Exception ex)
{
    Console.WriteLine("Failed with error info: {0}", ex.Message);
}
package main

import (
	"fmt"
	"github.com/aliyun/aliyun-oss-go-sdk/oss"
	"os"
)

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 {
		fmt.Println("Error:", err)
		os.Exit(-1)
	}

	// 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. 
	client, err := oss.New("yourEndpoint", "", "", oss.SetCredentialsProvider(&provider))
	if err != nil {
		fmt.Println("Error:", err)
		os.Exit(-1)
	}

	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 {
		fmt.Println("Error:", err)
		os.Exit(-1)
	}

	fmt.Println("Set Success")
}
#include <alibabacloud/oss/OssClient.h>
using namespace AlibabaCloud::OSS;

int main(void)
{
    /* Initialize information about the account that is used to access OSS. */
            
    /* 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. */
    std::string Endpoint = "yourEndpoint";
    /* Specify the name of the bucket. Example: examplebucket. */
    std::string BucketName = "examplebucket";

    /* Initialize resources such as network resources. */
    InitializeSdk();

    ClientConfiguration conf;
    /* 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. */
    auto credentialsProvider = std::make_shared<EnvironmentVariableCredentialsProvider>();
    OssClient client(Endpoint, credentialsProvider, conf);

    SetBucketCorsRequest request(BucketName);

    /* Configure CORS rules. */
    auto rule1 = CORSRule();
    /* Specify the origins from which cross-origin requests are allowed. */
    rule1.addAllowedOrigin("http://example.com");
    /* Specify the methods that can be used to send cross-origin requests, including GET, PUT, POST, DELETE, and HEAD. */
    rule1.addAllowedMethod("POST");
    /* Specify whether the headers that are specified by Access-Control-Request-Headers in the OPTIONS preflight request are allowed. */
    rule1.addAllowedHeader("*");
    /* Specify the response headers for allowed access requests from applications. */
    rule1.addExposeHeader("x-oss-test");
    /* You can configure up to 10 CORS rules for the bucket. */
    request.addCORSRule(rule1);

    auto rule2 = CORSRule();
    rule2.addAllowedOrigin("http://example.net");
    rule2.addAllowedMethod("GET");
    rule2.addExposeHeader("x-oss-test2");
    rule2.setMaxAgeSeconds(100);
    request.addCORSRule(rule2);

    auto outcome = client.SetBucketCors(request);

    if (!outcome.isSuccess()) {
        /* Handle exceptions. */
        std::cout << "SetBucketCors fail" <<
        ",code:" << outcome.error().Code() <<
        ",message:" << outcome.error().Message() <<
        ",requestId:" << outcome.error().RequestId() << std::endl;
        return -1;
    }

    /* Release resources such as network resources. */
    ShutdownSdk();
    return 0;
}
#include "oss_api.h"
#include "aos_http_io.h"
/* 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. */
const char *endpoint = "yourEndpoint";
/* Specify the name of the bucket. Example: examplebucket. */
const char *bucket_name = "examplebucket";
void init_options(oss_request_options_t *options)
{
    options->config = oss_config_create(options->pool);
    /* Use a char* string to initialize data of the aos_string_t type. */
    aos_str_set(&options->config->endpoint, endpoint);
    /* 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. */
    aos_str_set(&options->config->access_key_id, getenv("OSS_ACCESS_KEY_ID"));
    aos_str_set(&options->config->access_key_secret, getenv("OSS_ACCESS_KEY_SECRET"));
    /* Specify whether to use CNAME. The value 0 indicates that CNAME is not used. */
    options->config->is_cname = 0;
    /* Specify network parameters, such as the timeout period. */
    options->ctl = aos_http_controller_create(options->pool, 0);
}
int main(int argc, char *argv[])
{
    /* Call the aos_http_io_initialize method in main() to initialize global resources, such as network resources and memory resources. */
    if (aos_http_io_initialize(NULL, 0) != AOSE_OK) {
        exit(1);
    }
    /* Create a memory pool to manage memory. aos_pool_t is equivalent to apr_pool_t. The code used to create a memory pool is included in the APR library. */
    aos_pool_t *pool;
    /* Create a memory pool. The value of the second parameter is NULL. This value indicates that the pool does not inherit other memory pools. */
    aos_pool_create(&pool, NULL);
    /* Create and initialize options. This parameter includes global configuration information, such as endpoint, access_key_id, access_key_secret, is_cname, and curl. */
    oss_request_options_t *oss_client_options;
    /* Allocate the memory resources in the memory pool to the options. */
    oss_client_options = oss_request_options_create(pool);
    /* Initialize oss_client_options. */
    init_options(oss_client_options);
    /* Initialize the parameters. */
    aos_string_t bucket;
    aos_table_t *resp_headers = NULL; 
    aos_status_t *resp_status = NULL;
    aos_list_t cors_rule_list;
    oss_cors_rule_t *cors_rule1 = NULL, *cors_rule2 = NULL;
    aos_str_set(&bucket, bucket_name);
    aos_list_init(&cors_rule_list);
    cors_rule1 = oss_create_cors_rule(pool);
    aos_list_add_tail(&cors_rule1->node, &cors_rule_list);
    oss_create_sub_cors_rule(pool, &cors_rule1->allowed_origin_list, "allowed_origin_1_1");
    oss_create_sub_cors_rule(pool, &cors_rule1->allowed_origin_list, "allowed_origin_1_1");
    oss_create_sub_cors_rule(pool, &cors_rule1->allowed_method_list, "PUT");
    oss_create_sub_cors_rule(pool, &cors_rule1->allowed_method_list, "GET");
    oss_create_sub_cors_rule(pool, &cors_rule1->allowed_head_list, "Authorization");
    oss_create_sub_cors_rule(pool, &cors_rule1->expose_head_list, "expose_head_1_1");
    oss_create_sub_cors_rule(pool, &cors_rule1->expose_head_list, "expose_head_1_1");
    cors_rule2 = oss_create_cors_rule(pool);
    aos_list_add_tail(&cors_rule2->node, &cors_rule_list);
    oss_create_sub_cors_rule(pool, &cors_rule2->allowed_origin_list, "allowed_origin_2_1");
    oss_create_sub_cors_rule(pool, &cors_rule2->allowed_origin_list, "allowed_origin_2_2");
    oss_create_sub_cors_rule(pool, &cors_rule2->allowed_method_list, "PUT");
    oss_create_sub_cors_rule(pool, &cors_rule2->allowed_method_list, "GET");
    oss_create_sub_cors_rule(pool, &cors_rule2->allowed_head_list, "Authorization");
    oss_create_sub_cors_rule(pool, &cors_rule2->expose_head_list, "expose_head_2_1");
    oss_create_sub_cors_rule(pool, &cors_rule2->expose_head_list, "expose_head_2_2");
    /* Configure CORS rules. */
    resp_status = oss_put_bucket_cors(oss_client_options, &bucket, &cors_rule_list, &resp_headers);
    if (aos_status_is_ok(resp_status)) {
        printf("put bucket cors succeeded\n");
    } else {
        printf("put bucket cors failed\n");      
    }
    /* Release the memory pool. This operation releases the memory resources allocated for the request. */
    aos_pool_destroy(pool);
    /* Release the allocated global resources. */
    aos_http_io_deinitialize();
    return 0;
}
require 'aliyun/oss'

client = Aliyun::OSS::Client.new(
  # In this example, the endpoint of the China (Hangzhou) region is used. Specify your actual endpoint. 
  endpoint: 'https://oss-cn-hangzhou.aliyuncs.com',
  # 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. 
  access_key_id: ENV['OSS_ACCESS_KEY_ID'],
  access_key_secret: ENV['OSS_ACCESS_KEY_SECRET']
)

# Specify the name of the bucket. Example: examplebucket. 
bucket = client.get_bucket('examplebucket')
# Configure CORS rules. 
bucket.cors = [
    Aliyun::OSS::CORSRule.new(
      # Specify the origin from which you want to allow cross-origin requests. Example: http://example.com. 
      :allowed_origins => ['http://example.com', 'http://example.net'],
      # Specify the methods that can be used to send cross-origin requests, including GET, PUT, DELETE, POST, and HEAD. 
      :allowed_methods => ['PUT', 'POST', 'GET'],
      # Specify the headers that are allowed in OPTIONS preflight requests. Example: x-oss-test. 
      :allowed_headers => ['x-oss-test'],
      # Specify the response headers for allowed access requests from applications. 
      :expose_headers => ['x-oss-test1'],
      # Specify the period of time in which the browser can cache the response for an OPTIONS preflight request for specific resources. Unit: seconds. 
      :max_age_seconds => 100)
]

Use ossutil

For more information about how to configure CORS rules by using ossutil, see cors.

Use the OSS API

If your business requires a high level of customization, you can directly call RESTful APIs. To directly call an API, you must include the signature calculation in your code. For more information, see PutBucketcors.

FAQ

What do I do if the "No 'Access-Control-Allow-Origin'" error is reported?

For more information about the causes of and solutions to the error, see The "No 'Access-Control-Allow-Origin'" error persists when I call OSS after CORS rules are configured.

What do I do if a CORS error occurs when I use a CDN-accelerated domain name to access OSS?

If a CORS error occurs when you use a CDN-accelerated domain name to access OSS, you must configure CORS rules in the Alibaba Cloud CDN console. For more information, see Configure CORS.

What do I do if an error is reported indicating that the Access-Control-Allow-Origin header cannot be an asterisk (*) when I send a cross-origin request?

If the Response to preflight request doesn't pass access control check: The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'. error message is returned, change the value of Access-Control-Allow-Origin to specific URLs or specify xhr.withCredentials = false; in your code to fix the error. For more information, see How do I fix a cross-origin request error indicating that Access-Control-Allow-Origin cannot be an asterisk (*)?

Why are two CORS rules for the same bucket unable to apply to a request simultaneously?

If you configure two CORS rules, OSS matches the rules in sequence. After OSS finds the first match, OSS returns corresponding headers.