Elastic Compute Service (ECS) を使用して Web ページを作成する場合、バケット内の非公開イメージオブジェクトを使用する必要がある場合があります。特定の期間内に非公開イメージオブジェクトにアクセスする場合は、ossutil または Object Storage Service (OSS) SDK を使用して、イメージオブジェクトの有効期間が長い署名付き URL を生成できます。イメージオブジェクトへの不正アクセスを防ぐために、イメージオブジェクトが格納されているバケットのホットリンク保護も構成する必要があります。
ステップ 1: 署名付き URL を生成する
セキュリティ上の理由から、OSS コンソールで生成される URL のデフォルトの有効期間は 3,600 秒で、最大有効期間は 32,400 秒です。有効期間が 32,400 秒を超える署名付き URL を生成するには、ossutil または OSS SDK を使用します。
次のサンプルコードは、examplebucket という名前のバケット内の exampleobject.png という名前のオブジェクトの署名付き URL を生成し、署名付き URL が 30 日間有効であることを指定する方法の例を示しています。
ossutil を使用する
ossutil sign oss://examplebucket/exampleobject.png --timeout 2592000
サンプルコードを実行する前に、OSS_ACCESS_KEY_ID および OSS_ACCESS_KEY_SECRET 環境変数が構成されていることを確認してください。
OSS SDK を使用する
// この例では、中国 (杭州) リージョンのエンドポイントが使用されています。実際のエンドポイントを指定してください。
// In this example, the endpoint of the China (Hangzhou) region is used. Specify your actual endpoint.
import com.aliyun.oss.*;
import com.aliyun.oss.common.auth.*;
import java.net.URL;
import java.util.Date;
public class Demo {
public static void main(String[] args) throws Throwable {
String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
// エンドポイントにマッピングされるリージョンの ID を指定します。例: cn-hangzhou。
// Specify the ID of the region that maps to the endpoint. Example: cn-hangzhou.
String region = "cn-hangzhou";
// アクセスクレデンシャルをプロジェクトコードに保存しないことをお勧めします。そうしないと、アクセスクレデンシャルが漏洩し、アカウント内のすべてのリソースのセキュリティが損なわれる可能性があります。この例では、アクセスクレデンシャルは環境変数から取得されます。
// We recommend that you do not save access credentials in the project code. Otherwise, access credentials may be leaked, which compromises the security of all resources in your account. In this example, access credentials are obtained from environment variables.
EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
// バケットの名前を指定します。例: examplebucket。
// Specify the name of the bucket. Example: examplebucket.
String bucketName = "examplebucket";
// オブジェクトの完全なパスを指定します。例: exampleobject.png。完全なパスにバケット名を含めないでください。
// Specify the full path of the object. Example: exampleobject.png. Do not include the bucket name in the full path.
String objectName = "exampleobject.png";
// OSSClient インスタンスを作成します。
// Create an OSSClient instance.
// OSSClient が不要になったら、shutdown メソッドを呼び出してリソースを解放します。
// Call the shutdown method to release resources when the OSSClient is no longer in use.
ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
// V4 署名アルゴリズムの使用を明示的に宣言します。
// Explicitly declare the use of the V4 signature algorithm.
clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);
OSS ossClient = OSSClientBuilder.create()
.endpoint(endpoint)
.credentialsProvider(credentialsProvider)
.clientConfiguration(clientBuilderConfiguration)
.region(region)
.build();
try {
// 署名付き URL の有効期間を指定します。単位: 秒。この例では、有効期間は 30 日に設定されています。ビジネス要件に基づいて有効期間を構成できます。
// Specify the validity period of the signed URL. Unit: seconds. In this example, the validity period is set to 30 days. You can configure the validity period based on your business requirements.
// 現在のシステム時刻をミリ秒単位で取得します。
// Obtain the current system time in milliseconds.
long currentTimeMillis = System.currentTimeMillis();
// 30 日後の時刻を秒単位で計算します。
// Calculate the time after 30 days in seconds.
long expirationSeconds = currentTimeMillis/ 1000 + 30 * 24 * 3600;
// 30 日後の時刻を秒単位でミリ秒に変換して、Date パラメーターを構築します。
// Convert the time after 30 days in seconds to milliseconds to construct the Date parameter.
Date expiration = new Date(expirationSeconds * 1000);
// GET メソッドを使用してオブジェクトにアクセスするために使用される署名付き URL を生成します。ビジターは、URL の有効期限が切れる前に、ブラウザーに URL を入力してオブジェクトにアクセスできます。
// Generate the signed URL that is used to access the object by using GET methods. Visitors can enter the URL in a browser to access the object before the URL expires.
URL url = ossClient.generatePresignedUrl(bucketName, objectName, expiration);
System.out.println(url);
} 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();
}
}
}
}
<?php
// 環境変数からアクセスクレデンシャルを取得します。
// Obtain access credentials from environment variables.
if (is_file(__DIR__ . '/../autoload.php')) {
require_once __DIR__ . '/../autoload.php';
}
if (is_file(__DIR__ . '/../vendor/autoload.php')) {
require_once __DIR__ . '/../vendor/autoload.php';
}
use OSS\OssClient;
use OSS\Core\OssException;
use OSS\Http\RequestCore;
use OSS\Http\ResponseCore;
$accessKeyId = getenv("OSS_ACCESS_KEY_ID");
$accessKeySecret = getenv("OSS_ACCESS_KEY_SECRET");
// バケットが配置されているリージョンのエンドポイントを指定します。たとえば、バケットが中国 (杭州) リージョンにある場合は、エンドポイントを https://oss-cn-hangzhou.aliyuncs.com に設定します。
// Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com.
$endpoint = "yourEndpoint";
// バケットの名前を指定します。
// Specify the name of the bucket.
$bucket= "examplebucket";
// オブジェクトの完全なパスを指定します。完全なパスにバケット名を含めないでください。
// Specify the full path of the object. Do not include the bucket name in the full path.
$object = "exampleobject.txt";
// 署名付き URL の有効期間を指定します。単位: 秒。この例では、有効期間は 30 日に設定されています。ビジネス要件に基づいて有効期間を構成できます。
// Specify the validity period of the signed URL. Unit: seconds. In this example, the validity period is set to 30 days. You can configure the validity period based on your business requirements.
$timeout = 2592000;
try {
$ossClient = new OssClient($accessKeyId, $accessKeySecret, $endpoint, false);
// GetObject リクエストの署名付き URL を生成します。
// Generate a signed URL for the GetObject request.
$signedUrl = $ossClient->signUrl($bucket, $object, $timeout);
} catch (OssException $e) {
printf(__FUNCTION__ . ": FAILED\n");
printf($e->getMessage() . "\n");
return;
}
print(__FUNCTION__ . ": signedUrl: " . $signedUrl . "\n");
// コードで署名付き URL を使用するか、ブラウザーのアドレスバーに URL を入力してオブジェクトにアクセスできます。
// You can use the signed URL in your code or enter the URL in the address bar of a browser to access the object.
$request = new RequestCore($signedUrl);
// 署名付き URL にアクセスするために使用されるデフォルトのメソッドを GET に設定します。
// Set the default method that is used to access the signed URL to GET.
$request->set_method('GET');
$request->add_header('Content-Type', '');
$request->send_request();
$res = new ResponseCore($request->get_response_header(), $request->get_response_body(), $request->get_response_code());
if ($res->isOK()) {
print(__FUNCTION__ . ": OK" . "\n");
} else {
print(__FUNCTION__ . ": FAILED" . "\n");
};
# -*- coding: utf-8 -*-
// 環境変数からアクセスクレデンシャルを取得します。
// Obtain access credentials from environment variables.
import oss2
from oss2.credentials import EnvironmentVariableCredentialsProvider
import requests
auth = oss2.ProviderAuth(EnvironmentVariableCredentialsProvider())
// バケットが配置されているリージョンのエンドポイントを指定します。たとえば、バケットが中国 (杭州) リージョンにある場合は、エンドポイントを https://oss-cn-hangzhou.aliyuncs.com に設定します。
// Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com.
// バケットの名前を指定します。例: examplebucket。
// Specify the name of the bucket. Example: examplebucket.
bucket = oss2.Bucket(auth, 'yourEndpoint', 'examplebucket')
// オブジェクトの完全なパスを指定します。例: exampledir/exampleobject.txt。完全なパスにバケット名を含めないでください。
// Specify the full path of the object. Example: exampledir/exampleobject.txt. Do not include the bucket name in the full path.
object_name = 'exampledir/exampleobject.txt'
// 署名付き URL の有効期間を指定します。単位: 秒。この例では、有効期間は 30 日に設定されています。ビジネス要件に基づいて有効期間を構成できます。
// Specify the validity period of the signed URL. Unit: seconds. In this example, the validity period is set to 30 days. You can configure the validity period based on your business requirements.
// デフォルトでは、OSS は署名プロセスでオブジェクトの完全なパスにあるスラッシュ (/) をエスケープ文字として識別します。したがって、署名付き URL は直接使用できません。
// By default, OSS identifies forward slashes (/) in the full path of an object as escape characters in the signing process. Therefore, the signed URL cannot be directly used.
// slash_safe パラメーターを True に設定します。このようにして、OSS はオブジェクトの完全なパスにあるスラッシュ (/) をエスケープ文字として識別せず、署名付き URL を直接使用できます。
// Set the slash_safe parameter to True. This way, OSS does not identify the forward slashes (/) in the full path of the object as escape characters, and the signed URL can be directly used.
url = bucket.sign_url('GET', object_name, 2592000, slash_safe=True)
print('Signed URL: ', url)
// 署名付き URL を使用してオブジェクトをローカルコンピューターにダウンロードします。
// Use the signed URL to download the object to your local computer.
// ローカルファイルの完全なパスを指定します。例: D:\\localpath\\examplefile.txt。
// Specify the full path of the local file. Example: D:\\localpath\\examplefile.txt.
// デフォルトでは、examplefile.txt などのローカルファイルの名前を指定してもローカルパスを指定しない場合、ダウンロードされたオブジェクトはサンプルプログラムが属するプロジェクトのローカルパスに保存されます。
// By default, if you specify the name of a local file, such as examplefile.txt, but do not specify the local path, the downloaded object is saved to the local path of the project to which the sample program belongs.
result = bucket.get_object_with_url_to_file(url, 'D:\\localpath\\examplefile.txt')
print(result.read())
package main
import (
"fmt"
"os"
"github.com/aliyun/aliyun-oss-go-sdk/oss"
)
func main() {
/// 環境変数からアクセスクレデンシャルを取得します。
/// Obtain access credentials from environment variables.
provider, err := oss.NewEnvironmentVariableCredentialsProvider()
if err != nil {
fmt.Println("Error:", err)
os.Exit(-1)
}
// OSSClient インスタンスを作成します。
// Create an OSSClient instance.
// バケットが配置されているリージョンのエンドポイントを指定します。たとえば、バケットが中国 (杭州) リージョンにある場合は、エンドポイントを https://oss-cn-hangzhou.aliyuncs.com に設定します。実際のエンドポイントを指定してください。
// Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. Specify your actual endpoint.
client, err := oss.New("yourEndpoint", "", "", oss.SetCredentialsProvider(&provider))
if err != nil {
fmt.Println("Error:", err)
os.Exit(-1)
}
// バケットの名前を指定します。例: examplebucket。
// Specify the name of the bucket. Example: examplebucket.
bucketName := "examplebucket"
// オブジェクトの完全なパスを指定します。例: exampledir/exampleobject.txt。オブジェクトの完全なパスにバケット名を含めることはできません。
// Specify the full path of the object. Example: exampledir/exampleobject.txt. The full path of the object cannot contain the bucket name.
objectName := "exampledir/exampleobject.txt"
// オブジェクトをローカルパスにダウンロードし、ローカルファイルとして保存します。パスに同じ名前のファイルが既に存在する場合、ダウンロードされたオブジェクトはファイルを上書きします。パスに同じ名前のファイルが存在しない場合、ダウンロードされたオブジェクトはパスに保存されます。
// Download the object to the local path and store the object as a local file. If a file that has the same name already exists in the path, the downloaded object overwrites the file. If no file that has the same name exists in the path, the downloaded object is saved in the path.
// ダウンロードされたオブジェクトのローカルパスを指定しない場合、ダウンロードされたオブジェクトはサンプルプログラムが属するプロジェクトのパスに保存されます。
// If you do not specify a local path for the downloaded object, the downloaded object is saved to the path of the project to which the sample program belongs.
localDownloadedFilename := "D:\\localpath\\examplefile.txt"
// バケットの名前をクエリします。
// Query the name of the bucket.
bucket, err := client.Bucket(bucketName)
if err != nil {
HandleError(err)
}
// 署名付き URL の有効期間を指定します。単位: 秒。この例では、有効期間は 30 日に設定されています。ビジネス要件に基づいて有効期間を構成できます。
// Specify the validity period of the signed URL. Unit: seconds. In this example, the validity period is set to 30 days. You can configure the validity period based on your business requirements.
signedURL, err := bucket.SignURL(objectName, oss.HTTPGet, 2592000)
if err != nil {
HandleError(err)
}
body, err := bucket.GetObjectWithURL(signedURL)
if err != nil {
HandleError(err)
}
// オブジェクトのコンテンツを読み取ります。
// Read the content of the object.
data, err := ioutil.ReadAll(body)
body.Close()
data = data // ダウンロードされたデータを使用します。// Use the downloaded data.
// 署名付き URL を使用してオブジェクトをダウンロードし、ローカルファイルとして保存します。
// Use the signed URL to download the object and store the object as a local file.
err = bucket.GetObjectToFileWithURL(signedURL, localDownloadedFilename)
if err != nil {
HandleError(err)
}
}
using Aliyun.OSS;
using Aliyun.OSS.Common;
// バケットが配置されているリージョンのエンドポイントを指定します。たとえば、バケットが中国 (杭州) リージョンにある場合は、エンドポイントを https://oss-cn-hangzhou.aliyuncs.com に設定します。
// Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com.
var endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
// 環境変数からアクセスクレデンシャルを取得します。
// Obtain access credentials from environment variables.
var accessKeyId = Environment.GetEnvironmentVariable("OSS_ACCESS_KEY_ID");
var accessKeySecret = Environment.GetEnvironmentVariable("OSS_ACCESS_KEY_SECRET");
// バケットの名前を指定します。例: examplebucket。
// Specify the name of the bucket. Example: examplebucket.
var bucketName = "examplebucket";
// オブジェクトの完全なパスを指定します。完全なパスにバケット名を含めないでください。例: exampledir/exampleobject.txt。
// Specify the full path of the object. Do not include the bucket name in the full path. Example: exampledir/exampleobject.txt.
var objectName = "exampledir/exampleobject.txt";
// オブジェクトをダウンロードするローカルファイルの完全なパスを指定します。例: D:\\localpath\\examplefile.txt。パスに同じ名前のファイルが既に存在する場合、ダウンロードされたオブジェクトはファイルを上書きします。パスに同じ名前のファイルが存在しない場合、ダウンロードされたオブジェクトはパスに保存されます。
// Specify the full path of the local file to which you want to download the object. Example: D:\\localpath\\examplefile.txt. If a file that has the same name already exists in the path, the downloaded object overwrites the file. If no file that has the same name exists in the path, the downloaded object is saved in the path.
var downloadFilename = "D:\\localpath\\examplefile.txt";
// OSSClient インスタンスを作成します。
// Create an OSSClient instance.
var client = new OssClient(endpoint, accessKeyId, accessKeySecret);
try
{
var metadata = client.GetObjectMetadata(bucketName, objectName);
var etag = metadata.ETag;
// 署名付き URL を生成するリクエストを作成します。
// Create a request to generate a signed URL.
var req = new GeneratePresignedUriRequest(bucketName, objectName, SignHttpMethod.Get)
{
// 署名付き URL の有効期間を指定します。単位: 時間。この例では、有効期間は 30 日に設定されています。ビジネス要件に基づいて有効期間を構成できます。
// Specify the validity period of the signed URL. Unit: hours. In this example, the validity period is set to 30 days. You can configure the validity period based on your business requirements.
Expiration = DateTime.Now.AddHours(720),
};
var uri = client.GeneratePresignedUri(req);
// 署名付き URL を使用してオブジェクトをダウンロードします。
// Use the signed URL to download the object.
OssObject ossObject = client.GetObject(uri);
using (var file = File.Open(downloadFilename, FileMode.OpenOrCreate))
{
using (Stream stream = ossObject.Content)
{
int length;
int bufLength = 4 * 1024;
var buf = new byte[bufLength];
do
{
length = requestStream.Read(buf, 0, bufLength);
fs.Write(buf, 0, length);
} while (length != 0);
}
}
Console.WriteLine("Get object by signatrue succeeded. {0} ", uri.ToString());
}
catch (OssException ex)
{
Console.WriteLine("Failed with error code: {0}; Error info: {1}. \nRequestID:{2}\tHostID:{3}",
ex.ErrorCode, ex.Message, ex.RequestId, ex.HostId);
}
catch (Exception ex)
{
Console.WriteLine("Failed with error info: {0}", ex.Message);
}
#include <alibabacloud/oss/OssClient.h>
using namespace AlibabaCloud::OSS;
int main(void)
{
/* OSS にアクセスするために使用されるアカウントに関する情報を初期化します。*/
/* Initialize information about the account that is used to access OSS. */
/* バケットが配置されているリージョンのエンドポイントを指定します。たとえば、バケットが中国 (杭州) リージョンにある場合は、エンドポイントを https://oss-cn-hangzhou.aliyuncs.com に設定します。*/
/* Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. */
std::string Endpoint = "yourEndpoint";
/* バケットの名前を指定します。例: examplebucket。*/
/* Specify the name of the bucket. Example: examplebucket. */
std::string BucketName = "examplebucket";
/* オブジェクトの完全なパスを指定します。完全なパスにバケット名を含めないでください。例: exampledir/exampleobject.txt。*/
/* Specify the full path of the object. Do not include the bucket name in the full path. Example: exampledir/exampleobject.txt. */
std::string GetobjectUrlName = "exampledir/exampleobject.txt";
/* ネットワークリソースなどのリソースを初期化します。*/
/* Initialize resources, such as network resources. */
InitializeSdk();
ClientConfiguration conf;
/* 環境変数からアクセスクレデンシャルを取得します。*/
/* Obtain access credentials from environment variables. */
auto credentialsProvider = std::make_shared<EnvironmentVariableCredentialsProvider>();
OssClient client(Endpoint, credentialsProvider, conf);
/* 署名付き URL の有効期間を指定します。単位: 秒。この例では、有効期間は 30 日に設定されています。ビジネス要件に基づいて有効期間を構成できます。*/
/* Specify the validity period of the signed URL. Unit: seconds. In this example, the validity period is set to 30 days. You can configure the validity period based on your business requirements. */
std::time_t t = std::time(nullptr) + 2592000;
/* 署名付き URL を生成します。*/
/* Generate a signed URL. */
auto genOutcome = client.GeneratePresignedUrl(BucketName, GetobjectUrlName, t, Http::Get);
if (genOutcome.isSuccess()) {
std::cout << "GeneratePresignedUrl success, Gen url:" << genOutcome.result().c_str() << std::endl;
}
else {
/* 例外を処理します。*/
/* Handle exceptions. */
std::cout << "GeneratePresignedUrl fail" <<
",code:" << genOutcome.error().Code() <<
",message:" << genOutcome.error().Message() <<
",requestId:" << genOutcome.error().RequestId() << std::endl;
ShutdownSdk();
return -1;
}
/* 署名付き URL を使用してオブジェクトをダウンロードします。*/
/* Use the signed URL to download the object. */
auto outcome = client.GetObjectByUrl(genOutcome.result());
if (!outcome.isSuccess()) {
/* 例外を処理します。*/
/* Handle exceptions. */
std::cout << "GetObjectByUrl fail" <<
",code:" << outcome.error().Code() <<
",message:" << outcome.error().Message() <<
",requestId:" << outcome.error().RequestId() << std::endl;
ShutdownSdk();
return -1;
}
/* ネットワークリソースなどのリソースを解放します。*/
/* Release resources, such as network resources. */
ShutdownSdk();
return 0;
}
ステップ 2: ホットリンク保護を構成する
バケットの Referer ホワイトリストを構成して、バケット内のリソースへの不正アクセスを防ぐことができます。
たとえば、examplebucket という名前のバケットのホットリンク保護を構成できます。このようにすると、Referer フィールドの値が http://www.example.com
であるリクエストのみが許可されます。ホットリンク保護を構成するには、次の手順を実行します。
OSS コンソール にログインします。
左側のナビゲーションウィンドウで、[バケット] をクリックします。[バケット] ページで、examplebucket をクリックします。
左側のナビゲーションツリーで、[コンテンツセキュリティ] > [ホットリンク保護] を選択します。
[ホットリンク保護] ページで、[ホットリンク保護] をオンにします。
[Referer ホワイトリスト] フィールドに、
http://www.example.com
と入力します。[空の Referer を許可する] を [いいえ] に設定して、Referer フィールドが空のリクエストを拒否します。
[QueryString を切り捨てる] を [はい] または [いいえ] に設定します。
はい: Referer のクエリ文字列が削除されます。たとえば、ホットリンク保護構成の Referer が
http://www.example.com/?action=nop
の場合、クエリ文字列が削除され、http://www.example.com/
が Referer と照合するために使用されます。いいえ: Referer のクエリ文字列は削除されません。たとえば、ホットリンク保護構成の Referer が
http://www.example.com/?action=nop
の場合、http://www.example.com/?action=nop
が Referer と照合するために使用されます。クエリ文字列の解析の詳細については、「クエリ文字列の解析ルール」をご参照ください。
[保存] をクリックします。
Referer の詳細については、「ホットリンク保護」をご参照ください。