All Products
Search
Document Center

Object Storage Service:Configure CORS (Java SDK)

Last Updated:Jul 31, 2025

Because of the same-origin policy of browsers, cross-origin requests are denied when data is exchanged or resources are shared between different domain names. To resolve this issue, you can set a cross-origin access policy to allow access from specified domain names, methods, and request headers.

Precautions

  • In this topic, the public endpoint of the China (Hangzhou) region is used. To access OSS from other Alibaba Cloud services in the same region, use an internal endpoint. For details about supported regions and endpoints, 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 Configuration examples for common scenarios.

  • To set a cross-origin rule, you must have the oss:PutBucketCors permission. To retrieve cross-origin rules, you must have the oss:GetBucketCors permission. To delete cross-origin rules, you must have the oss:DeleteBucketCors permission. For more information, see Attach a custom policy to a RAM user.

Set a cross-origin rule

The following code provides an example of how to set a cross-origin rule for a specified bucket:

import com.aliyun.oss.*; import com.aliyun.oss.common.auth.*; import com.aliyun.oss.common.comm.SignVersion; 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 the actual endpoint. String endpoint = "https://oss-cn-hangzhou.aliyuncs.com"; // Obtain access credentials from environment variables. Before you run this 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 bucket name. Example: examplebucket. String bucketName = "examplebucket"; // 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. String region = "cn-hangzhou"; // Create an OSSClient instance. // When the OSSClient instance is no longer used, call the shutdown method to release the resources. ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration(); clientBuilderConfiguration.setSignatureVersion(SignVersion.V4); OSS ossClient = OSSClientBuilder.create() .endpoint(endpoint) .credentialsProvider(credentialsProvider) .clientConfiguration(clientBuilderConfiguration) .region(region) .build(); try { SetBucketCORSRequest request = new SetBucketCORSRequest(bucketName); // You can set a maximum of 10 cross-origin rules for each bucket. ArrayList<SetBucketCORSRequest.CORSRule> putCorsRules = new ArrayList<SetBucketCORSRequest.CORSRule>(); SetBucketCORSRequest.CORSRule corRule = new SetBucketCORSRequest.CORSRule(); ArrayList<String> allowedOrigin = new ArrayList<String>(); // Specify the allowed origins of cross-origin requests. allowedOrigin.add( "http://example.com"); ArrayList<String> allowedMethod = new ArrayList<String>(); // Specify the allowed methods for cross-origin requests (GET, PUT, DELETE, POST, and HEAD). allowedMethod.add("GET"); ArrayList<String> allowedHeader = new ArrayList<String>(); // Specify whether to allow the headers specified by the Access-Control-Request-Headers header in the preflight OPTIONS request. allowedHeader.add("x-oss-test"); ArrayList<String> exposedHeader = new ArrayList<String>(); // Specify the response headers that users are allowed to access from applications. exposedHeader.add("x-oss-test1"); // AllowedOrigins and AllowedMethods support at most one asterisk (*) wildcard character. The asterisk (*) indicates that all domain sources 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 cache time for the results of preflight (OPTIONS) requests for specific resources in the browser. Unit: seconds. corRule.setMaxAgeSeconds(10); // A maximum of 10 rules are allowed. putCorsRules.add(corRule); // The existing 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 under any circumstances. // 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(); } } } }

Retrieve cross-origin rules

The following code provides an example of how to retrieve cross-origin rules:

import com.aliyun.oss.*; import com.aliyun.oss.common.auth.*; import com.aliyun.oss.common.comm.SignVersion; 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 the actual endpoint. String endpoint = "https://oss-cn-hangzhou.aliyuncs.com"; // Obtain access credentials from environment variables. Before you run this 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 bucket name. Example: examplebucket. String bucketName = "examplebucket"; // 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. String region = "cn-hangzhou"; // Create an OSSClient instance. // When the OSSClient instance is no longer used, call the shutdown method to release the resources. ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration(); clientBuilderConfiguration.setSignatureVersion(SignVersion.V4); OSS ossClient = OSSClientBuilder.create() .endpoint(endpoint) .credentialsProvider(credentialsProvider) .clientConfiguration(clientBuilderConfiguration) .region(region) .build(); try { ArrayList<SetBucketCORSRequest.CORSRule> corsRules; // Retrieve the cross-origin rules. corsRules = (ArrayList<SetBucketCORSRequest.CORSRule>) ossClient.getBucketCORSRules(bucketName); for (SetBucketCORSRequest.CORSRule rule : corsRules) { for (String allowedOrigin1 : rule.getAllowedOrigins()) { // Retrieve the allowed origins of cross-origin requests. System.out.println(allowedOrigin1); } for (String allowedMethod1 : rule.getAllowedMethods()) { // Retrieve the allowed methods for cross-origin requests. System.out.println(allowedMethod1); } if (rule.getAllowedHeaders().size() > 0){ for (String allowedHeader1 : rule.getAllowedHeaders()) { // Retrieve the allowed response headers for cross-origin requests. System.out.println(allowedHeader1); } } if (rule.getExposeHeaders().size() > 0) { for (String exposeHeader : rule.getExposeHeaders()) { // Retrieve the response headers that users are allowed to access 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 cross-origin rules

The following code provides an example of how to delete all cross-origin rules for a specified bucket:

import com.aliyun.oss.*; import com.aliyun.oss.common.auth.*; import com.aliyun.oss.common.comm.SignVersion; public class Demo { public static void main(String[] args) throws Exception { // In this example, the endpoint of the China (Hangzhou) region is used. Specify the actual endpoint. String endpoint = "https://oss-cn-hangzhou.aliyuncs.com"; // Obtain access credentials from environment variables. Before you run this 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 bucket name. Example: examplebucket. String bucketName = "examplebucket"; // 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. String region = "cn-hangzhou"; // Create an OSSClient instance. // When the OSSClient instance is no longer used, call the shutdown method to release the resources. ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration(); clientBuilderConfiguration.setSignatureVersion(SignVersion.V4); OSS ossClient = OSSClientBuilder.create() .endpoint(endpoint) .credentialsProvider(credentialsProvider) .clientConfiguration(clientBuilderConfiguration) .region(region) .build(); try { // Delete all cross-origin 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 used to set cross-origin rules, see GitHub.

  • For more information about the API operation for setting cross-origin rules, see PutBucketCors.

  • For more information about the API operation for retrieving cross-origin rules, see GetBucketCors.

  • For more information about the API operation for deleting cross-origin rules, see DeleteBucketCors.