Tarayıcıların aynı kaynak politikası nedeniyle, farklı alan adları arasında veri alışverişi yapılırken veya kaynaklar paylaşılırken çapraz kaynak istekleri reddedilebilir. Bu sorunu çözmek için çapraz kaynak paylaşımı (CORS) kuralları yapılandırabilirsiniz. CORS kurallarında, istek gönderilebilecek alan adlarını, çapraz kaynak isteklerini göndermek için kullanılabilecek yöntemleri ve izin verilen üst bilgileri belirtebilirsiniz.
Kullanım notları
-
Bu konuda China (Hangzhou) bölgesinin genel uç noktası kullanılmaktadır. Aynı bölgedeki diğer Alibaba Cloud hizmetlerinden OSS'e erişmek için dahili bir uç nokta kullanın. Desteklenen bölgeler ve uç noktalar hakkında ayrıntılı bilgi için bkz. Bölgeler ve uç noktalar.
-
Bu konuda erişim kimlik bilgileri ortam değişkenlerinden alınır. Daha fazla bilgi için bkz. Erişim kimlik bilgilerini yapılandırma.
-
Bu konu, bir OSS uç noktası ile bir OSSClient örneği oluşturmayı göstermektedir. Özel bir alan adı kullanmak veya Security Token Service (STS) kimlik bilgileriyle kimlik doğrulaması yapmak gibi alternatif yapılandırmalar için bkz. İstemci yapılandırması.
-
CORS kurallarını yapılandırmak için
oss:PutBucketCorsiznine sahip olmanız gerekir. CORS kurallarını sorgulamak içinoss:GetBucketCorsiznine sahip olmanız gerekir. CORS kurallarını silmek içinoss:DeleteBucketCorsiznine sahip olmanız gerekir. Daha fazla bilgi için bkz. Özel bir ilke atama.
CORS kuralı yapılandırma
Aşağıdaki örnek kod, belirli bir paket için CORS kuralının nasıl yapılandırılacağını göstermektedir:
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();
}
}
}
}
CORS kurallarını sorgulama
Aşağıdaki örnek kod, belirli bir paketin CORS kurallarının nasıl sorgulanacağını göstermektedir:
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();
}
}
}
}
CORS kurallarını silme
Aşağıdaki örnek kod, belirli bir paketin tüm CORS kurallarının nasıl silineceğini göstermektedir:
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();
}
}
}
}
İlgili konular
-
CORS kurallarını yönetmek için kullanılan tam örnek kodu görüntülemek üzere GitHub adresini ziyaret edin.
-
CORS kurallarını yapılandırmak için çağırabileceğiniz API işlemi hakkında daha fazla bilgi için bkz. PutBucketCors.
-
CORS kurallarını sorgulamak için çağırabileceğiniz API işlemi hakkında daha fazla bilgi için bkz. GetBucketCors.
-
CORS kurallarını silmek için çağırabileceğiniz API işlemi hakkında daha fazla bilgi için bkz. DeleteBucketCors.