デフォルトでは、Object Storage Service (OSS) バケット内のオブジェクトのアクセス制御リスト (ACL) は非公開です。オブジェクト所有者のみがオブジェクトにアクセスする権限を持っています。このトピックでは、OSS SDK for Python を使用して、ユーザーが HTTP GET メソッドを使用して指定された期間内に特定のオブジェクトをダウンロードできる署名付き URL を生成する方法について説明します。有効期間内であれば、ユーザーは署名付き URL を使用してオブジェクトに繰り返しアクセスできます。署名付き URL の有効期限が切れた場合は、署名付き URL を再生成してユーザーのアクセスを延長できます。
考慮事項
OSS でサポートされているリージョンとエンドポイント間のマッピングの詳細については、「OSS のリージョンとエンドポイント」をご参照ください。
HTTP GET リクエストを許可する署名付き URL を生成する場合、
oss:GetObject権限が必要です。詳細については、「RAM ユーザーへのカスタム権限の付与」をご参照ください。説明OSS SDK for Python を使用して署名付き URL を生成する場合、SDK はローカルコンピューターに保存されているキー情報に基づいて特定のアルゴリズムを使用して署名を計算し、URL の有効性とセキュリティを確保するために署名を URL に追加します。署名の計算と URL の構築はクライアント側で実行され、ネットワーク経由でサーバーにリクエストを送信することはありません。したがって、署名付き URL を生成するために特定の権限は必要ありません。ただし、サードパーティユーザーがリソースに対して意図した操作を実行できるようにするには、署名付き URL を生成する ID プリンシパルが、その操作を実行するための対応する権限を持っていることを確認してください。
このトピックでは、V4 署名を含み、最大 7 日間の有効期間を持つ署名付き URL が使用されます。詳細については、「署名バージョン 4 (推奨)」をご参照ください。
プロセス
次のフローチャートは、署名付き URL を使用してオブジェクトをダウンロードする方法を示しています。
サンプルコード
HTTP GET リクエストを許可する署名付き URL を生成します:
import Client from '@aliyun/oss'; // OSS クライアントインスタンスを作成します const client = new Client({ // Security Token Service (STS) から取得した AccessKey ID を指定します。 accessKeyId: 'yourAccessKeyId', // STS から取得した AccessKey シークレットを指定します。 accessKeySecret: 'yourAccessKeySecret', // STS から取得したセキュリティトークンを指定します。 securityToken: 'yourSecurityToken', // アクセスするバケットのリージョンを指定します。たとえば、バケットが中国 (杭州) リージョンにある場合は、リージョンを oss-cn-hangzhou に設定します。 region: 'oss-cn-hangzhou', }); // バケットの名前を指定します。 const bucket = 'yourBucketName'; // 署名付き URL を生成するオブジェクトの名前を指定します。 const key = 'yourObjectName'; /** * オブジェクトを取得するための署名付き URL を生成します。 * signatureUrl メソッドを使用して GET リクエストの署名付き URL を生成します。デフォルトでは Client.options.signVersion が使用されます。 */ const signatureUrlForGetObject = async () => { /** * 署名バージョンが明示的に指定されていない場合、デフォルトで Client.options.signVersion が使用されます。 */ const url = await client.signatureUrl({ bucket, // バケットの名前を指定します。 key, // オブジェクトの名前を指定します。 expires: 60 * 60, // 有効期限を 60 分 (秒単位) に設定します。 }); // 生成された署名付き URL を出力します console.log(url); }; signatureUrlForGetObject();署名付き URL を使用してオブジェクトをダウンロードします。
curl
curl -SO "https://examplebucket.oss-cn-hangzhou.aliyuncs.com/exampleobject.txt?x-oss-date=20241112T092756Z&x-oss-expires=3599&x-oss-signature-version=OSS4-HMAC-SHA256&x-oss-credential=LTAI****************/20241112/cn-hangzhou/oss/aliyun_v4_request&x-oss-signature=ed5a******************************************************"Java
import java.io.BufferedInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.URL; public class Demo { public static void main(String[] args) { // HTTP GET リクエストを許可する署名付き URL を指定します。 String fileURL = "https://examplebucket.oss-cn-hangzhou.aliyuncs.com/exampleobject.txt?x-oss-date=20241112T092756Z&x-oss-expires=3599&x-oss-signature-version=OSS4-HMAC-SHA256&x-oss-credential=LTAI****************/20241112/cn-hangzhou/oss/aliyun_v4_request&x-oss-signature=ed5a******************************************************"; // ダウンロードしたオブジェクトを格納するパスを、オブジェクト名と拡張子を含めて指定します。 String savePath = "C:/downloads/myfile.txt"; try { downloadFile(fileURL, savePath); System.out.println("Download completed!"); } catch (IOException e) { System.err.println("Error during download: " + e.getMessage()); } } private static void downloadFile(String fileURL, String savePath) throws IOException { URL url = new URL(fileURL); HttpURLConnection httpConn = (HttpURLConnection) url.openConnection(); httpConn.setRequestMethod("GET"); // 応答コードを指定します。 int responseCode = httpConn.getResponseCode(); if (responseCode == HttpURLConnection.HTTP_OK) { // 入力ストリームを設定します。 InputStream inputStream = new BufferedInputStream(httpConn.getInputStream()); // 出力ストリームを設定します。 FileOutputStream outputStream = new FileOutputStream(savePath); byte[] buffer=new byte[4096]; // バッファーのサイズを指定します。 int bytesRead; while ((bytesRead = inputStream.read(buffer)) != -1) { outputStream.write(buffer, 0, bytesRead); } outputStream.close(); inputStream.close(); } else { System.out.println("No file to download. Server replied HTTP code: " + responseCode); } httpConn.disconnect(); } }Node.js
const https = require('https'); const fs = require('fs'); const fileURL = "https://examplebucket.oss-cn-hangzhou.aliyuncs.com/exampleobject.txt?x-oss-date=20241112T092756Z&x-oss-expires=3599&x-oss-signature-version=OSS4-HMAC-SHA256&x-oss-credential=LTAI****************/20241112/cn-hangzhou/oss/aliyun_v4_request&x-oss-signature=ed5a******************************************************"; const savePath = "C:/downloads/myfile.txt"; https.get(fileURL, (response) => { if (response.statusCode === 200) { const fileStream = fs.createWriteStream(savePath); response.pipe(fileStream); fileStream.on('finish', () => { fileStream.close(); console.log("Download completed!"); }); } else { console.error(`Download failed. Server responded with code: ${response.statusCode}`); } }).on('error', (err) => { console.error("Error during download:", err.message); });Python
import requests file_url = "https://examplebucket.oss-cn-hangzhou.aliyuncs.com/exampleobject.txt?x-oss-date=20241112T092756Z&x-oss-expires=3599&x-oss-signature-version=OSS4-HMAC-SHA256&x-oss-credential=LTAI****************/20241112/cn-hangzhou/oss/aliyun_v4_request&x-oss-signature=ed5a******************************************************" save_path = "C:/downloads/myfile.txt" try: response = requests.get(file_url, stream=True) if response.status_code == 200: with open(save_path, 'wb') as f: for chunk in response.iter_content(4096): f.write(chunk) print("Download completed!") else: print(f"No file to download. Server replied HTTP code: {response.status_code}") except Exception as e: print("Error during download:", e)Go
package main import ( "io" "net/http" "os" ) func main() { fileURL := "https://examplebucket.oss-cn-hangzhou.aliyuncs.com/exampleobject.txt?x-oss-date=20241112T092756Z&x-oss-expires=3599&x-oss-signature-version=OSS4-HMAC-SHA256&x-oss-credential=LTAI****************/20241112/cn-hangzhou/oss/aliyun_v4_request&x-oss-signature=ed5a******************************************************" savePath := "C:/downloads/myfile.txt" response, err := http.Get(fileURL) if err != nil { panic(err) } defer response.Body.Close() if response.StatusCode == http.StatusOK { outFile, err := os.Create(savePath) if err != nil { panic(err) } defer outFile.Close() _, err = io.Copy(outFile, response.Body) if err != nil { panic(err) } println("Download completed!") } else { println("No file to download. Server replied HTTP code:", response.StatusCode) } }JavaScript
const fileURL = "https://examplebucket.oss-cn-hangzhou.aliyuncs.com/exampleobject.txt?x-oss-date=20241112T092756Z&x-oss-expires=3599&x-oss-signature-version=OSS4-HMAC-SHA256&x-oss-credential=LTAI****************/20241112/cn-hangzhou/oss/aliyun_v4_request&x-oss-signature=ed5a******************************************************"; const savePath = "C:/downloads/myfile.txt"; // ダウンロードしたオブジェクトの名前を指定します。 fetch(fileURL) .then(response => { if (!response.ok) { throw new Error(`Server replied HTTP code: ${response.status}`); } return response.blob(); // 応答のタイプを blob に変更します。 }) .then(blob => { const link = document.createElement('a'); link.href = window.URL.createObjectURL(blob); link.download=savePath; // ダウンロードしたオブジェクトの名前を指定します。 document.body.appendChild(link); // このステップにより、署名付き URL がドキュメントに存在することが保証されます。 link.click(); // 署名付き URL をクリックして、オブジェクトのダウンロードをシミュレートします。 link.remove(); // オブジェクトがダウンロードされた後、署名付き URL を削除します。 console.log("Download completed!"); }) .catch(error => { console.error("Error during download:", error); });Android-Java
import android.os.AsyncTask; import android.os.Environment; import java.io.BufferedInputStream; import java.io.FileOutputStream; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.URL; public class DownloadTask extends AsyncTask<String, String, String> { @Override protected String doInBackground(String... params) { String fileURL = params[0]; String savePath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) + "/myfile.txt"; // ダウンロードしたオブジェクトを保存するパスを指定します。 try { URL url = new URL(fileURL); HttpURLConnection httpConn = (HttpURLConnection) url.openConnection(); httpConn.setRequestMethod("GET"); int responseCode = httpConn.getResponseCode(); if (responseCode == HttpURLConnection.HTTP_OK) { InputStream inputStream = new BufferedInputStream(httpConn.getInputStream()); FileOutputStream outputStream = new FileOutputStream(savePath); byte[] buffer = new byte[4096]; int bytesRead; while ((bytesRead = inputStream.read(buffer)) != -1) { outputStream.write(buffer, 0, bytesRead); } outputStream.close(); inputStream.close(); return "Download completed!"; } else { return "No file to download. Server replied HTTP code: " + responseCode; } } catch (Exception e) { return "Error during download: " + e.getMessage(); } } }Objective-C
#import <Foundation/Foundation.h> int main(int argc, const char * argv[]) { @autoreleasepool { // 署名付き URL とオブジェクトを保存するパスを指定します。 NSString *fileURL = @"https://examplebucket.oss-cn-hangzhou.aliyuncs.com/exampleobject.txt?x-oss-date=20241112T092756Z&x-oss-expires=3599&x-oss-signature-version=OSS4-HMAC-SHA256&x-oss-credential=LTAI****************/20241112/cn-hangzhou/oss/aliyun_v4_request&x-oss-signature=ed5a******************************************************"; NSString *savePath = @"/Users/your_username/Desktop/myfile.txt"; // your_username をユーザー名に置き換えます。 // URL オブジェクトを作成します。 NSURL *url = [NSURL URLWithString:fileURL]; // オブジェクトダウンロードタスクを作成します。 NSURLSessionDataTask *task = [[NSURLSession sharedSession] dataTaskWithURL:url completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) { // エラーを処理します。 if (error) { NSLog(@"Error during download: %@", error.localizedDescription); return; } // オブジェクト内のデータを確認します。 if (!data) { NSLog(@"No data received."); return; } // オブジェクトを保存します。 NSError *writeError = nil; BOOL success = [data writeToURL:[NSURL fileURLWithPath:savePath] options:NSDataWritingAtomic error:&writeError]; if (success) { NSLog(@"Download completed!"); } else { NSLog(@"Error saving file: %@", writeError.localizedDescription); } }]; // オブジェクトダウンロードタスクを開始します。 [task resume]; // 非同期リクエストを完了するためにメインスレッドを実行し続けます。 [[NSRunLoop currentRunLoop] run]; } return 0; }