All Products
Search
Document Center

Object Storage Service:CORS

Last Updated:Dec 20, 2023

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 by using other Alibaba Cloud services in the same region as OSS, use an internal endpoint. For more information about the regions and endpoints supported by OSS, see 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.

  • 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 Create an OSSClient instance.

  • 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.

Configure a CORS rule

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

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();
            }
        }
    }
}

Query CORS rules

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

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 {
            ArrayList<SetBucketCORSRequest.CORSRule> corsRules;
            // Query the CORS rules. 
            corsRules =  (ArrayList<SetBucketCORSRequest.CORSRule>) ossClient.getBucketCORSRules(bucketName);
            for (SetBucketCORSRequest.CORSRule rule : corsRules) {
                for (String allowedOrigin1 : rule.getAllowedOrigins()) {
                    // Query the origins from which cross-origin requests are allowed. 
                    System.out.println(allowedOrigin1);
                }

                for (String allowedMethod1 : rule.getAllowedMethods()) {
                    // Query the HTTP methods that cross-origin requests are allowed to use. 
                    System.out.println(allowedMethod1);
                }

                if (rule.getAllowedHeaders().size() > 0){
                    for (String allowedHeader1 : rule.getAllowedHeaders()) {
                        // Query the response headers that are included in the cross-origin requests. 
                        System.out.println(allowedHeader1);
                    }
                }

                if (rule.getExposeHeaders().size() > 0) {
                    for (String exposeHeader : rule.getExposeHeaders()) {
                        // Query the response headers for allowed access requests from applications. 
                        System.out.println(exposeHeader);
                    }
                }

                if ( null != rule.getMaxAgeSeconds()) {
                    System.out.println(rule.getMaxAgeSeconds());
                }
            }
        } 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();
            }
        }
    }
}

Delete CORS rules

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

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;

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 {
            // Delete all CORS rules of the bucket. 
            ossClient.deleteBucketCORSRules(bucketName);
        } 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();
            }
        }
    }
}

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 PutBucketCors.

  • 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.