因瀏覽器的同源策略限制,在不同網域名稱之間進行資料互動或者資源共用時,會出現跨域請求被拒絕的問題。您可以通過設定允許特定的網域名稱、方法和要求標頭的跨域存取原則,解決跨域問題。
注意事項
本文以華東1(杭州)外網Endpoint為例。如果您希望通過與OSS同地區的其他阿里雲產品訪問OSS,請使用內網Endpoint。關於OSS支援的Region與Endpoint的對應關係,請參見OSS訪問網域名稱、資料中心、開放連接埠。
本文以從環境變數讀取存取憑證為例。如何配置訪問憑證,請參見Java配置訪問憑證。
本文以OSS網域名稱建立OSSClient為例。如果您希望通過自訂網域名、STS等方式建立OSSClient,請參見建立OSSClient。
要設定跨域規則,您必須有
oss:PutBucketCors
許可權;要擷取跨域規則,您必須有oss:GetBucketCors
許可權;要刪除跨域規則,您必須有oss:DeleteBucketCors
許可權。具體操作,請參見為RAM使用者授權自訂的權限原則。
設定跨域規則
以下代碼用於設定指定儲存空間的跨域規則:
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 {
// Endpoint以華東1(杭州)為例,其它Region請按實際情況填寫。
String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
// 從環境變數中擷取訪問憑證。運行本程式碼範例之前,請確保已設定環境變數OSS_ACCESS_KEY_ID和OSS_ACCESS_KEY_SECRET。
EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
// 填寫Bucket名稱,例如examplebucket。
String bucketName = "examplebucket";
// 填寫Bucket所在地區。以華東1(杭州)為例,Region填寫為cn-hangzhou。
String region = "cn-hangzhou";
// 建立OSSClient執行個體。
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);
// 每個儲存空間最多允許設定10條跨域規則。
ArrayList<SetBucketCORSRequest.CORSRule> putCorsRules = new ArrayList<SetBucketCORSRequest.CORSRule>();
SetBucketCORSRequest.CORSRule corRule = new SetBucketCORSRequest.CORSRule();
ArrayList<String> allowedOrigin = new ArrayList<String>();
// 指定允許跨域請求的來源。
allowedOrigin.add( "http://example.com");
ArrayList<String> allowedMethod = new ArrayList<String>();
// 指定允許的跨域要求方法(GET/PUT/DELETE/POST/HEAD)。
allowedMethod.add("GET");
ArrayList<String> allowedHeader = new ArrayList<String>();
// 是否允許預取指令(OPTIONS)中Access-Control-Request-Headers頭中指定的Header。
allowedHeader.add("x-oss-test");
ArrayList<String> exposedHeader = new ArrayList<String>();
// 指定允許使用者從應用程式中訪問的回應標頭。
exposedHeader.add("x-oss-test1");
// AllowedOrigins和AllowedMethods最多支援一個星號(*)萬用字元。星號(*)表示允許所有的域來源或者操作。
corRule.setAllowedMethods(allowedMethod);
corRule.setAllowedOrigins(allowedOrigin);
// AllowedHeaders和ExposeHeaders不支援萬用字元。
corRule.setAllowedHeaders(allowedHeader);
corRule.setExposeHeaders(exposedHeader);
// 指定瀏覽器對特定資源的預取(OPTIONS)請求返回結果的緩衝時間,單位為秒。
corRule.setMaxAgeSeconds(10);
// 最多允許10條規則。
putCorsRules.add(corRule);
// 已存在的規則將被覆蓋。
request.setCorsRules(putCorsRules);
// 指定是否返回Vary: Origin頭。指定為TRUE,表示不管發送的是否為跨域請求或跨域請求是否成功,均會返回Vary: Origin頭。指定為False,表示任何情況下都不會返回Vary: Origin頭。
// 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();
}
}
}
}
擷取跨域規則
以下代碼用於擷取跨域規則:
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 {
// Endpoint以華東1(杭州)為例,其它Region請按實際情況填寫。
String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
// 從環境變數中擷取訪問憑證。運行本程式碼範例之前,請確保已設定環境變數OSS_ACCESS_KEY_ID和OSS_ACCESS_KEY_SECRET。
EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
// 填寫Bucket名稱,例如examplebucket。
String bucketName = "examplebucket";
// 填寫Bucket所在地區。以華東1(杭州)為例,Region填寫為cn-hangzhou。
String region = "cn-hangzhou";
// 建立OSSClient執行個體。
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;
// 擷取跨域規則。
corsRules = (ArrayList<SetBucketCORSRequest.CORSRule>) ossClient.getBucketCORSRules(bucketName);
for (SetBucketCORSRequest.CORSRule rule : corsRules) {
for (String allowedOrigin1 : rule.getAllowedOrigins()) {
// 擷取允許的跨域請求源。
System.out.println(allowedOrigin1);
}
for (String allowedMethod1 : rule.getAllowedMethods()) {
// 擷取允許的跨域要求方法。
System.out.println(allowedMethod1);
}
if (rule.getAllowedHeaders().size() > 0){
for (String allowedHeader1 : rule.getAllowedHeaders()) {
// 擷取允許跨域請求的回應標頭。
System.out.println(allowedHeader1);
}
}
if (rule.getExposeHeaders().size() > 0) {
for (String exposeHeader : rule.getExposeHeaders()) {
// 擷取允許使用者從應用程式中訪問的回應標頭。
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();
}
}
}
}
刪除跨域規則
以下代碼用於刪除指定儲存空間的所有跨域規則:
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 {
// Endpoint以華東1(杭州)為例,其它Region請按實際情況填寫。
String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
// 從環境變數中擷取訪問憑證。運行本程式碼範例之前,請確保已設定環境變數OSS_ACCESS_KEY_ID和OSS_ACCESS_KEY_SECRET。
EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
// 填寫Bucket名稱,例如examplebucket。
String bucketName = "examplebucket";
// 填寫Bucket所在地區。以華東1(杭州)為例,Region填寫為cn-hangzhou。
String region = "cn-hangzhou";
// 建立OSSClient執行個體。
ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);
OSS ossClient = OSSClientBuilder.create()
.endpoint(endpoint)
.credentialsProvider(credentialsProvider)
.clientConfiguration(clientBuilderConfiguration)
.region(region)
.build();
try {
// 刪除儲存空間所有跨域規則。
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();
}
}
}
}
相關文檔
關於跨網域設定的完整範例程式碼,請參見GitHub樣本。
關於設定跨域規則的API介面說明,請參見PutBucketCors。
關於擷取跨域規則的API介面說明,請參見GetBucketCors。
關於刪除跨域規則的API介面說明,請參見DeleteBucketCors。