ブラウザの同一オリジンポリシーにより、異なるドメイン間でデータを交換したりリソースを共有したりする際のクロスオリジンリクエストは拒否されます。この問題を解決するには、オリジン間リソース共有 (CORS) ルールを設定して、特定のドメイン名、メソッド、リクエストヘッダーからのアクセスを許可します。
注意事項
この Topic では、中国 (杭州) リージョンのパブリックエンドポイントを使用します。同じリージョン内の他の Alibaba Cloud サービスから OSS にアクセスするには、内部エンドポイントを使用します。サポートされているリージョンとエンドポイントの詳細については、「リージョンとエンドポイント」をご参照ください。
この Topic では、アクセス認証情報は環境変数から取得されます。アクセス認証情報の設定方法の詳細については、「アクセス認証情報の設定」をご参照ください。
この Topic では、OSS エンドポイントを使用して OSSClient インスタンスが作成されます。カスタムドメイン名またはセキュリティトークンサービス (STS) を使用して OSSClient インスタンスを作成する場合は、「一般的なシナリオの設定例」をご参照ください。
CORS ルールを設定するには、
oss:PutBucketCors権限が必要です。CORS ルールを取得するには、oss:GetBucketCors権限が必要です。CORS ルールを削除するには、oss:DeleteBucketCors権限が必要です。詳細については、「RAM ユーザーへのカスタムポリシーのアタッチ」をご参照ください。
CORS ルールの設定
次のコードは、指定されたバケットの CORS ルールを設定する方法を示しています。
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 {
// この例では、中国 (杭州) リージョンのエンドポイントを使用します。実際のエンドポイントに置き換えてください。
String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
// 環境変数からアクセス認証情報を取得します。このコードを実行する前に、OSS_ACCESS_KEY_ID および OSS_ACCESS_KEY_SECRET 環境変数が設定されていることを確認してください。
EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
// バケット名を指定します (例: examplebucket)。
String bucketName = "examplebucket";
// バケットが配置されているリージョンを指定します。たとえば、バケットが中国 (杭州) リージョンにある場合は、リージョンを cn-hangzhou に設定します。
String region = "cn-hangzhou";
// OSSClient インスタンスを作成します。
// 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 個の CORS ルールを設定できます。
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 で指定されたヘッダーを許可するかどうかを指定します。
allowedHeader.add("x-oss-test");
ArrayList<String> exposedHeader = new ArrayList<String>();
// ユーザーがアプリケーションからアクセスできるレスポンスヘッダーを指定します。
exposedHeader.add("x-oss-test1");
// AllowedOrigins と AllowedMethods は、最大 1 つのアスタリスク (*) ワイルドカードをサポートします。アスタリスク (*) は、すべてのオリジンまたは操作が許可されることを示します。
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();
}
}
}
}CORS ルールの取得
次のコードは、指定されたバケットの CORS ルールを取得する方法を示しています。
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 {
// この例では、中国 (杭州) リージョンのエンドポイントを使用します。実際のエンドポイントに置き換えてください。
String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
// 環境変数からアクセス認証情報を取得します。このコードを実行する前に、OSS_ACCESS_KEY_ID および OSS_ACCESS_KEY_SECRET 環境変数が設定されていることを確認してください。
EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
// バケット名を指定します (例: examplebucket)。
String bucketName = "examplebucket";
// バケットが配置されているリージョンを指定します。たとえば、バケットが中国 (杭州) リージョンにある場合は、リージョンを cn-hangzhou に設定します。
String region = "cn-hangzhou";
// OSSClient インスタンスを作成します。
// 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;
// CORS ルールを取得します。
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();
}
}
}
}CORS ルールの削除
次のコードは、指定されたバケットのすべての CORS ルールを削除する方法を示しています。
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 {
// この例では、中国 (杭州) リージョンのエンドポイントを使用します。実際のエンドポイントに置き換えてください。
String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
// 環境変数からアクセス認証情報を取得します。このコードを実行する前に、OSS_ACCESS_KEY_ID および OSS_ACCESS_KEY_SECRET 環境変数が設定されていることを確認してください。
EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
// バケット名を指定します (例: examplebucket)。
String bucketName = "examplebucket";
// バケットが配置されているリージョンを指定します。たとえば、バケットが中国 (杭州) リージョンにある場合は、リージョンを cn-hangzhou に設定します。
String region = "cn-hangzhou";
// OSSClient インスタンスを作成します。
// OSSClient インスタンスが不要になったら、シャットダウンメソッドを呼び出してリソースを解放します。
ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);
OSS ossClient = OSSClientBuilder.create()
.endpoint(endpoint)
.credentialsProvider(credentialsProvider)
.clientConfiguration(clientBuilderConfiguration)
.region(region)
.build();
try {
// バケットのすべての CORS ルールを削除します。
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();
}
}
}
}関連ドキュメント
CORS ルールを設定するための完全なサンプルコードについては、「GitHub の例」をご参照ください。
CORS ルールを設定するための API 操作の詳細については、「PutBucketCors」をご参照ください。
CORS ルールを取得するための API 操作の詳細については、「GetBucketCors」をご参照ください。
CORS ルールを削除するための API 操作の詳細については、「DeleteBucketCors」をご参照ください。