En raison de la politique d'origine unique des navigateurs, les requêtes inter-origines peuvent être rejetées lors de l'échange de données ou du partage de ressources entre différents noms de domaine. Pour résoudre ce problème, vous pouvez configurer des règles de partage de ressources entre origines (CORS). Dans ces règles, spécifiez les noms de domaine autorisés à envoyer des requêtes, les méthodes utilisables pour les requêtes inter-origines et les en-têtes autorisés.
Notes d'utilisation
Cette rubrique utilise le point de terminaison public de la région Chine (Hangzhou). Pour accéder à OSS depuis d'autres services Alibaba Cloud dans la même région, utilisez un point de terminaison interne. Pour plus de détails sur les régions et points de terminaison pris en charge, consultez Régions et points de terminaison.
Dans cette rubrique, les identifiants d'accès sont obtenus à partir des variables d'environnement. Pour plus d'informations, consultez Configurer les informations d'identification d'accès.
Cette rubrique illustre la création d'une instance OSSClient avec un endpoint OSS. Pour d'autres configurations, telles que l'utilisation d'un domaine personnalisé ou l'authentification avec des identifiants du Security Token Service (STS), consultez Configuration du client.
Pour configurer des règles CORS, vous devez disposer de l'autorisation
oss:PutBucketCors. Pour interroger les règles CORS, vous devez disposer de l'autorisationoss:GetBucketCors. Pour supprimer des règles CORS, vous devez disposer de l'autorisationoss:DeleteBucketCors. Pour plus d'informations, consultez Accorder une stratégie personnalisée.
Configurer une règle CORS
L'exemple de code suivant montre comment configurer une règle CORS pour un bucket spécifique :
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 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";
// 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.
// Call the shutdown method to release resources when the OSSClient is no longer in use.
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 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();
}
}
}
}
Interroger les règles CORS
L'exemple de code suivant montre comment interroger les règles CORS d'un bucket spécifique :
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 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";
// 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.
// Call the shutdown method to release resources when the OSSClient is no longer in use.
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;
// 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();
}
}
}
}
Supprimer des règles CORS
L'exemple de code suivant montre comment supprimer toutes les règles CORS d'un bucket spécifique :
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 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";
// 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.
// Call the shutdown method to release resources when the OSSClient is no longer in use.
ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);
OSS ossClient = OSSClientBuilder.create()
.endpoint(endpoint)
.credentialsProvider(credentialsProvider)
.clientConfiguration(clientBuilderConfiguration)
.region(region)
.build();
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();
}
}
}
}
Références
Pour obtenir l'exemple de code complet utilisé pour gérer les règles CORS, visitez GitHub.
Pour plus d'informations sur l'opération API permettant de configurer des règles CORS, consultez PutBucketCors.
Pour plus d'informations sur l'opération API permettant d'interroger les règles CORS, consultez GetBucketCors.
Pour plus d'informations sur l'opération API permettant de supprimer des règles CORS, consultez DeleteBucketCors.