View a markdown version of this page

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

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

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

您可以使用 AWS 帳戶 或 IAM 使用者安全登入資料,將已驗證的請求傳送至 Amazon S3。本節提供如何使用 適用於 Java 的 AWS SDK 適用於 .NET 的 AWS SDK、 和 傳送已驗證請求的範例 適用於 PHP 的 AWS SDK。如需 AWS SDKs的清單,請前往範例程式碼和程式庫

每個這些 AWS SDKs都使用開發套件特定的登入資料提供者鏈結來尋找和使用登入資料,並代表登入資料擁有者執行動作。所有這些登入資料提供者鏈結都有的共同之處是,它們都會尋找您的本機 AWS 登入資料檔案。

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

建立本機 AWS 登入資料檔案

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

  1. 登入 AWS 管理主控台 並開啟位於 https://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 SDKs 搭配使用。

使用 AWS SDKs 傳送已驗證的請求

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

Java

如需有關使用適用於 Java 的 AWS SDK 驗證請求的資訊,請參閱《 AWS SDKs和工具參考指南》中的使用共用組態和登入資料檔案來全域設定 SDK 和工具以及使用 AWS SDKs 和工具進行身分驗證和存取。 AWS SDKs

.NET

若要使用 AWS 帳戶 或 IAM 使用者登入資料傳送已驗證的請求:

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

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

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

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

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

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

下列 C# 範例會說明如何執行前述作業。如需有關設定和執行程式碼範例的資訊,請參閱《適用於 .NET 的 AWS SDK 開發人員指南》中的適用於 .NET 的 SDK 入門AWS

範例
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); } } } }
PHP

本節說明如何使用 第 3 版的類別 適用於 PHP 的 AWS SDK ,使用您的 AWS 帳戶 或 IAM 使用者登入資料傳送已驗證的請求。如需適用於 Ruby 的 AWS SDK API 的詳細資訊,請前往AWS 適用於 Ruby 的 SDK - 第 2 版

下列 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 會傳回錯誤。如需詳細資訊,請參閱 適用於 PHP 的 AWS SDK 文件中的建立匿名用戶端

Ruby

您必須先設定 SDK AWS 用來驗證儲存貯體和物件存取權的存取憑證,才能使用 第 3 版來 適用於 Ruby 的 AWS SDK 呼叫 Amazon S3。如果您已在本機系統的登入資料設定檔中設定共用 AWS 登入資料,則適用於 Ruby 的 SDK 第 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, 'amzn-s3-demo-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 true rescue StandardError => e puts "Error while accessing the bucket named '#{bucket_name}': #{e.message}" 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, 'amzn-s3-demo-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 true rescue StandardError => e puts "Error while accessing the bucket named '#{bucket_name}': #{e.message}" 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
範例

下列範例使用 SDK for Go 從共用 AWS 登入資料檔案自動載入的登入資料。

package main import ( "context" "errors" "fmt" "github.com/aws/aws-sdk-go-v2/config" "github.com/aws/aws-sdk-go-v2/service/s3" "github.com/aws/smithy-go" ) // 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() { ctx := context.Background() sdkConfig, err := config.LoadDefaultConfig(ctx) 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(ctx, &s3.ListBucketsInput{}) if err != nil { var ae smithy.APIError if errors.As(err, &ae) && ae.ErrorCode() == "AccessDenied" { fmt.Println("You don't have permission to list buckets for this account.") } else { 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) } } }

相關資源