使用 AWS 帳戶 或 IAM 使用者登入資料提出請求 - Amazon Simple Storage Service

本文為英文版的機器翻譯版本,如內容有任何歧義或不一致之處,概以英文版為準。

使用 AWS 帳戶 或 IAM 使用者登入資料提出請求

您可以使用 AWS 帳戶 或 IAM 使用者安全登入資料,將經過身分驗證的請求傳送至 Amazon S3。本節示範如何使用 AWS SDK for Java、AWS SDK for .NET和AWS SDK for PHP傳送經過身分驗證的請求。如需可用的 AWS 開發套件清單,請前往範本程式碼與程式庫

上述每個 AWS 開發套件都會使用開發套件專屬的登入資料提供者鏈結,來尋找並使用登入資料,並代替登入資料擁有者執行動作。這些所有登入資料提供者鏈結的共通之處,在於都會尋找您的本機 AWS 登入資料檔案。

如需詳細資訊,請參閱下列主題。

建立本機 AWS 登入資料檔案

為 AWS 開發套件設定登入資料最簡單的方法是使用 AWS 登入資料檔案。若使用 AWS Command Line Interface (AWS CLI),您可能已設定好了本機 AWS 登入資料檔案。若非如此,請使用下列程序來設定登入資料檔案:

  1. 登入 AWS Management Console,並開啟位於 https://console.aws.amazon.com/iam/ 的 IAM 主控台。

  2. 建立新的使用者,使其許可受限在希望程式碼可以存取的服務與動作。如需建立新使用者的詳細資訊,請參閱建立 IAM 使用者 (主控台),並遵循直到步驟 8 的指示執行作業。

  3. 選擇 Download .csv (下載 .csv) 並在本機儲存 AWS 登入資料複本。

  4. 在您的電腦上,瀏覽至主目錄並建立 .aws 目錄。在 Unix 系統上 (例如 Linux 或 OS X),其會是下列位置:

    ~/.aws

    在 Windows 上,其會是下列位置:

    %HOMEPATH%\.aws
  5. .aws 目錄中,建立稱為 credentials 的新檔案。

  6. 開啟您從 IAM 主控台下載的憑證 .csv 檔案,並使用下列格式將其內容複製到 credentials 檔案:

    [default] aws_access_key_id = your_access_key_id aws_secret_access_key = your_secret_access_key
  7. 儲存 credentials 檔案,然後刪除在步驟 3 中所下載的 .csv 檔案。

目前即已於您的本機電腦上設定好了分享登入資料檔案,可與 AWS 開發套件搭配使用。

使用 AWS 開發套件傳送經驗證的請求

使用 AWS 開發套件傳送經驗證的請求。如需傳送已驗證請求的詳細資訊,請參閱 AWS 安全憑證IAM Identity Center 驗證

Java

若您要傳送使用 AWS 帳戶 或 IAM 使用者登入資料,將經過身分驗證的請求傳送至 Amazon S3,請依以下操作:

  • 使用 AmazonS3ClientBuilder 類別建立 AmazonS3Client 執行個體。

  • 執行其中一個 AmazonS3Client 方法,將請求傳送至 Amazon S3。用戶端會從您所提供的登入資料產生必要的簽章,並在要求中包含此簽章。

下列範例會執行前述作業:如需建立及測試工作範例的資訊,請參閱「測試 Amazon S3 Java 程式碼範例」。

import com.amazonaws.AmazonServiceException; import com.amazonaws.SdkClientException; import com.amazonaws.auth.profile.ProfileCredentialsProvider; import com.amazonaws.regions.Regions; import com.amazonaws.services.s3.AmazonS3; import com.amazonaws.services.s3.AmazonS3ClientBuilder; import com.amazonaws.services.s3.model.ListObjectsRequest; import com.amazonaws.services.s3.model.ObjectListing; import com.amazonaws.services.s3.model.S3ObjectSummary; import java.io.IOException; import java.util.List; public class MakingRequests { public static void main(String[] args) throws IOException { Regions clientRegion = Regions.DEFAULT_REGION; String bucketName = "*** Bucket name ***"; try { AmazonS3 s3Client = AmazonS3ClientBuilder.standard() .withCredentials(new ProfileCredentialsProvider()) .withRegion(clientRegion) .build(); // Get a list of objects in the bucket, two at a time, and // print the name and size of each object. ListObjectsRequest listRequest = new ListObjectsRequest().withBucketName(bucketName).withMaxKeys(2); ObjectListing objects = s3Client.listObjects(listRequest); while (true) { List<S3ObjectSummary> summaries = objects.getObjectSummaries(); for (S3ObjectSummary summary : summaries) { System.out.printf("Object \"%s\" retrieved with size %d\n", summary.getKey(), summary.getSize()); } if (objects.isTruncated()) { objects = s3Client.listNextBatchOfObjects(objects); } else { break; } } } catch (AmazonServiceException e) { // The call was transmitted successfully, but Amazon S3 couldn't process // it, so it returned an error response. e.printStackTrace(); } catch (SdkClientException e) { // Amazon S3 couldn't be contacted for a response, or the client // couldn't parse the response from Amazon S3. e.printStackTrace(); } } }
.NET

若您要使用 AWS 帳戶 或 IAM 使用者登入資料來傳送經過身分驗證的請求,請遵循以下步驟:

  • 建立 AmazonS3Client 類別的執行個體。

  • 執行其中一個 AmazonS3Client 方法,將請求傳送至 Amazon S3。用戶端會從您所提供的登入資料產生必要的簽章,並在傳送給 Amazon S3 的請求中包含此簽章。

如需詳細資訊,請參閱「使用 AWS 帳戶 或 IAM 使用者登入資料提出請求」。

注意
  • 您可以建立 AmazonS3Client 用戶端,而無須提供您的安全登入資料。使用此用戶端傳送的要求,是沒有簽章的匿名要求。若針對非公有存取的資源傳送匿名要求,Amazon S3 會傳回錯誤。

  • 您可以建立 AWS 帳戶 並建立所需的使用者。您也可以管理這些使用者的登入資料。您需要這些登入資料才能執行下列範例中的任務。如需詳細資訊,請參閱《AWS SDK for .NET 開發人員指南》中的設定 AWS 憑證

    然後,您也可以將應用程式設定為主動擷取設定檔和登入資料,然後在建立 AWS 服務用戶端時明確使用這些登入資料。如需詳細資訊,請參閱《AWS SDK for .NET 開發人員指南》中的在應用程式中存取登入資料和設定檔

下列 C# 範例會說明如何執行前述作業。如需執行本指南中 .NET 範例的資訊,以及如何將您的登入資料存放在組態檔中的指示,請參閱「執行 Amazon S3 .NET 程式碼範例」。

using Amazon; using Amazon.S3; using Amazon.S3.Model; using System; using System.Threading.Tasks; namespace Amazon.DocSamples.S3 { class MakeS3RequestTest { private const string bucketName = "*** bucket name ***"; // Specify your bucket region (an example region is shown). private static readonly RegionEndpoint bucketRegion = RegionEndpoint.USWest2; private static IAmazonS3 client; public static void Main() { using (client = new AmazonS3Client(bucketRegion)) { Console.WriteLine("Listing objects stored in a bucket"); ListingObjectsAsync().Wait(); } } static async Task ListingObjectsAsync() { try { ListObjectsRequest request = new ListObjectsRequest { BucketName = bucketName, MaxKeys = 2 }; do { ListObjectsResponse response = await client.ListObjectsAsync(request); // Process the response. foreach (S3Object entry in response.S3Objects) { Console.WriteLine("key = {0} size = {1}", entry.Key, entry.Size); } // If the response is truncated, set the marker to get the next // set of keys. if (response.IsTruncated) { request.Marker = response.NextMarker; } else { request = null; } } while (request != null); } catch (AmazonS3Exception e) { Console.WriteLine("Error encountered on server. Message:'{0}' when writing an object", e.Message); } catch (Exception e) { Console.WriteLine("Unknown encountered on server. Message:'{0}' when writing an object", e.Message); } } } }

如需工作範例,請參閱「Amazon S3 物件概觀」與「儲存貯體概觀」。您可以使用 AWS 帳戶 或 IAM 使用者登入資料來測試這些範例。

例如,若要列出儲存貯體中的所有物件金鑰,請參閱「以程式設計方式列出物件索引鍵」。

PHP

本節說明如何利用 AWS SDK for PHP 第 3 版的類別,來傳送使用您的 AWS 帳戶 或 IAM 使用者登入資料完成驗證的請求。文中假設您已遵循「使用 AWS SDK for PHP 和運行 PHP 示例」中的說明執行作業,且已正確安裝 AWS SDK for PHP。

下列 PHP 範例說明用戶端如何使用您的安全登入資料提出要求,以列出您帳戶的所有儲存貯體。

require 'vendor/autoload.php'; use Aws\S3\Exception\S3Exception; use Aws\S3\S3Client; $bucket = '*** Your Bucket Name ***'; $s3 = new S3Client([ 'region' => 'us-east-1', 'version' => 'latest', ]); // Retrieve the list of buckets. $result = $s3->listBuckets(); try { // Retrieve a paginator for listing objects. $objects = $s3->getPaginator('ListObjects', [ 'Bucket' => $bucket ]); echo "Keys retrieved!" . PHP_EOL; // Print the list of objects to the page. foreach ($objects as $object) { echo $object['Key'] . PHP_EOL; } } catch (S3Exception $e) { echo $e->getMessage() . PHP_EOL; }
注意

您可以建立 S3Client 用戶端,而無須提供您的安全登入資料。使用此用戶端傳送的要求,是沒有簽章的匿名要求。若針對非公有存取的資源傳送匿名要求,Amazon S3 會傳回錯誤。如需詳細資訊,請參閱 AWS SDK for PHP 文件中的建立匿名用戶端

如需運作範例,請參閱「Amazon S3 物件概觀」。您可以使用 AWS 帳戶 或 IAM 使用者登入資料來測試這些範例。

如需列出儲存貯體中物件金鑰的範例,請參閱「以程式設計方式列出物件索引鍵」。

Ruby

您必須設定開發套件用來驗證儲存貯體與物件存取的 AWS 存取登入資料,才能使用 AWS SDK for Ruby 的第 3 版呼叫 Amazon S3。如果您分享了本機系統上 AWS 登入資料描述檔中設定的登入資料,適用於 Ruby 的開發套件第 3 版即可使用這些登入資料,而不需要在您的程式碼中進行宣告。如需設定分享之登入資料的詳細資訊,請參閱「使用 AWS 帳戶 或 IAM 使用者登入資料提出請求」。

下列 Ruby 程式碼片段,使用本機電腦上分享之 AWS 登入資料檔案中的登入資料來驗證請求,以取得指定儲存貯體中的物件金鑰。會執行以下項目:

  1. 建立 Aws::S3::Client 類別的執行個體。

  2. 使用 list_objects_v2Aws::S3::Client 方法列舉儲存貯體中的物件,對 Amazon S3 提出要求。用戶端會從您電腦上 AWS 登入資料檔案中的登入資料產生必要的簽章值,並在傳送至 Amazon S3 的請求中包含此值。

  3. 將物件金鑰名稱陣列,列印至終端機。

# Prerequisites: # - An existing Amazon S3 bucket. require "aws-sdk-s3" # @param s3_client [Aws::S3::Client] An initialized Amazon S3 client. # @param bucket_name [String] The bucket's name. # @return [Boolean] true if all operations succeed; otherwise, false. # @example # s3_client = Aws::S3::Client.new(region: 'us-west-2') # exit 1 unless list_bucket_objects?(s3_client, 'doc-example-bucket') def list_bucket_objects?(s3_client, bucket_name) puts "Accessing the bucket named '#{bucket_name}'..." objects = s3_client.list_objects_v2( bucket: bucket_name, max_keys: 50 ) if objects.count.positive? puts "The object keys in this bucket are (first 50 objects):" objects.contents.each do |object| puts object.key end else puts "No objects found in this bucket." end return true rescue StandardError => e puts "Error while accessing the bucket named '#{bucket_name}': #{e.message}" return false end # Example usage: def run_me region = "us-west-2" bucket_name = "BUCKET_NAME" s3_client = Aws::S3::Client.new(region: region) exit 1 unless list_bucket_objects?(s3_client, bucket_name) end run_me if $PROGRAM_NAME == __FILE__

如果您沒有本機 AWS 登入資料檔案,您仍然可以建立 Aws::S3::Client 資源,並對 Amazon S3 儲存貯體與物件執行程式碼。使用適用於 Ruby 的開發套件第 3 版傳送請求,預設是沒有簽章的匿名請求。若針對非公有存取的資源傳送匿名請求,Amazon S3 會傳回錯誤。

您可以針對適用於 Ruby 的開發套件應用程式使用並展開上述程式碼片段,如下列更強大的範例所示。

# Prerequisites: # - An existing Amazon S3 bucket. require "aws-sdk-s3" # @param s3_client [Aws::S3::Client] An initialized Amazon S3 client. # @param bucket_name [String] The bucket's name. # @return [Boolean] true if all operations succeed; otherwise, false. # @example # s3_client = Aws::S3::Client.new(region: 'us-west-2') # exit 1 unless list_bucket_objects?(s3_client, 'doc-example-bucket') def list_bucket_objects?(s3_client, bucket_name) puts "Accessing the bucket named '#{bucket_name}'..." objects = s3_client.list_objects_v2( bucket: bucket_name, max_keys: 50 ) if objects.count.positive? puts "The object keys in this bucket are (first 50 objects):" objects.contents.each do |object| puts object.key end else puts "No objects found in this bucket." end return true rescue StandardError => e puts "Error while accessing the bucket named '#{bucket_name}': #{e.message}" return false end # Example usage: def run_me region = "us-west-2" bucket_name = "BUCKET_NAME" s3_client = Aws::S3::Client.new(region: region) exit 1 unless list_bucket_objects?(s3_client, bucket_name) end run_me if $PROGRAM_NAME == __FILE__
Go

以下範例使用的 AWS 憑證是由適用於 Go 的 SDK 自動從共用憑證檔案載入。

package main import ( "context" "fmt" "github.com/aws/aws-sdk-go-v2/config" "github.com/aws/aws-sdk-go-v2/service/s3" ) // main uses the AWS SDK for Go V2 to create an Amazon Simple Storage Service // (Amazon S3) client and list up to 10 buckets in your account. // This example uses the default settings specified in your shared credentials // and config files. func main() { sdkConfig, err := config.LoadDefaultConfig(context.TODO()) if err != nil { fmt.Println("Couldn't load default configuration. Have you set up your AWS account?") fmt.Println(err) return } s3Client := s3.NewFromConfig(sdkConfig) count := 10 fmt.Printf("Let's list up to %v buckets for your account.\n", count) result, err := s3Client.ListBuckets(context.TODO(), &s3.ListBucketsInput{}) if err != nil { fmt.Printf("Couldn't list buckets for your account. Here's why: %v\n", err) return } if len(result.Buckets) == 0 { fmt.Println("You don't have any buckets!") } else { if count > len(result.Buckets) { count = len(result.Buckets) } for _, bucket := range result.Buckets[:count] { fmt.Printf("\t%v\n", *bucket.Name) } } }

相關資源