IAM 사용자 임시 자격 증명을 사용하여 요청하기 - Amazon Simple Storage Service

IAM 사용자 임시 자격 증명을 사용하여 요청하기

AWS 계정 또는 IAM 사용자는 임시 보안 자격 증명을 요청한 후 이 자격 증명을 사용하여 Amazon S3에 인증된 요청을 전송할 수 있습니다. 이 섹션에서는 AWS SDK for Java, .NET 및 PHP를 사용하여 임시 보안 자격 증명을 구하고 이 자격 증명을 사용하여 Amazon S3 요청을 인증하는 방법에 대한 예제를 제공합니다.

Java

IAM 사용자 또는 AWS 계정은 AWS SDK for Java를 사용하여 임시 보안 자격 증명을 요청(요청 만들기 참조)한 후 이 자격 증명을 사용하여 Amazon S3에 액세스할 수 있습니다. 세션의 지정된 유효 기간이 만료된 후 이 자격 증명도 만료됩니다.

세션은 기본적으로 1시간 동안 지속됩니다. IAM 사용자 자격 증명을 사용하는 경우, 임시 보안 자격 증명을 요청할 수 있는 기간을 15분에서 역할의 최대 세션 기간까지 지정할 수 있습니다. 임시 보안 자격 증명에 대한 자세한 내용은 IAM 사용 설명서임시 보안 자격 증명을 참조하세요. 요청 생성에 대한 자세한 내용은 요청 만들기 섹션을 참조하세요.

임시 보안 자격 증명 가져오기 및 Amazon S3에 액세스
  1. AWSSecurityTokenService 클래스의 인스턴스를 만듭니다. 자격 증명 제공에 대한 자세한 내용은 AWS SDK 및 Explorer를 사용하여 Amazon S3로 개발 단원을 참조하십시오.

  2. Security Token Service(STS) 클라이언트의 assumeRole() 메서드를 호출하여 원하는 역할에 대한 임시 보안 자격 증명을 검색합니다.

  3. BasicSessionCredentials 객체에 임시 보안 자격 증명을 패키지로 포함합니다. 이 객체를 사용하여 Amazon S3 클라이언트에 임시 보안 자격 증명을 제공합니다.

  4. 임시 보안 자격 증명을 사용하여 AmazonS3Client 클래스의 인스턴스를 만듭니다. 이 클라이언트를 사용하여 Amazon S3에 요청을 보냅니다. 만료된 자격 증명을 사용하여 요청을 보낼 경우 Amazon S3에서 오류를 반환합니다.

참고

AWS 계정 보안 자격 증명을 사용하여 획득한 임시 자격 증명의 유효 기간은 1시간입니다. IAM 사용자 자격 증명을 사용하여 세션을 요청할 경우에만 세션 기간을 지정할 수 있습니다.

다음 예제는 지정된 버킷의 객체 키 세트를 나열합니다. 이 예제에서는 세션에 대한 임시 보안 자격 증명을 구한 다음 이러한 자격 증명을 사용하여 Amazon S3에 인증된 요청을 보냅니다.

IAM 사용자 자격 증명을 사용하여 샘플을 테스트하려면 AWS 계정에서 IAM 사용자를 생성해야 합니다. IAM 사용자를 만드는 방법에 대한 자세한 내용은 IAM 사용 설명서의 첫 번째 IAM 사용자 및 관리자 그룹 생성을 참조하세요.

실제 예제를 작성 및 테스트하는 방법에 대한 자세한 내용은 Amazon S3 Java 코드 예제 테스트 섹션을 참조하세요.

import com.amazonaws.AmazonServiceException; import com.amazonaws.SdkClientException; import com.amazonaws.auth.AWSStaticCredentialsProvider; import com.amazonaws.auth.BasicSessionCredentials; import com.amazonaws.auth.profile.ProfileCredentialsProvider; import com.amazonaws.services.s3.AmazonS3; import com.amazonaws.services.s3.AmazonS3ClientBuilder; import com.amazonaws.services.s3.model.ObjectListing; import com.amazonaws.services.securitytoken.AWSSecurityTokenService; import com.amazonaws.services.securitytoken.AWSSecurityTokenServiceClientBuilder; import com.amazonaws.services.securitytoken.model.AssumeRoleRequest; import com.amazonaws.services.securitytoken.model.AssumeRoleResult; import com.amazonaws.services.securitytoken.model.Credentials; public class MakingRequestsWithIAMTempCredentials { public static void main(String[] args) { String clientRegion = "*** Client region ***"; String roleARN = "*** ARN for role to be assumed ***"; String roleSessionName = "*** Role session name ***"; String bucketName = "*** Bucket name ***"; try { // Creating the STS client is part of your trusted code. It has // the security credentials you use to obtain temporary security credentials. AWSSecurityTokenService stsClient = AWSSecurityTokenServiceClientBuilder.standard() .withCredentials(new ProfileCredentialsProvider()) .withRegion(clientRegion) .build(); // Obtain credentials for the IAM role. Note that you cannot assume the role of // an AWS root account; // Amazon S3 will deny access. You must use credentials for an IAM user or an // IAM role. AssumeRoleRequest roleRequest = new AssumeRoleRequest() .withRoleArn(roleARN) .withRoleSessionName(roleSessionName); AssumeRoleResult roleResponse = stsClient.assumeRole(roleRequest); Credentials sessionCredentials = roleResponse.getCredentials(); // Create a BasicSessionCredentials object that contains the credentials you // just retrieved. BasicSessionCredentials awsCredentials = new BasicSessionCredentials( sessionCredentials.getAccessKeyId(), sessionCredentials.getSecretAccessKey(), sessionCredentials.getSessionToken()); // Provide temporary security credentials so that the Amazon S3 client // can send authenticated requests to Amazon S3. You create the client // using the sessionCredentials object. AmazonS3 s3Client = AmazonS3ClientBuilder.standard() .withCredentials(new AWSStaticCredentialsProvider(awsCredentials)) .withRegion(clientRegion) .build(); // Verify that assuming the role worked and the permissions are set correctly // by getting a set of object keys from the bucket. ObjectListing objects = s3Client.listObjects(bucketName); System.out.println("No. of Objects: " + objects.getObjectSummaries().size()); } 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

IAM 사용자 또는 AWS 계정은 AWS SDK for .NET을 사용하여 임시 보안 자격 증명을 요청한 후 이 자격 증명을 사용하여 Amazon S3에 액세스할 수 있습니다. 세션의 유효 기간이 만료된 후 이 자격 증명도 만료됩니다.

세션은 기본적으로 1시간 동안 지속됩니다. IAM 사용자 자격 증명을 사용하는 경우, 임시 보안 자격 증명을 요청할 수 있는 기간을 15분에서 역할의 최대 세션 기간까지 지정할 수 있습니다. 임시 보안 자격 증명에 대한 자세한 내용은 IAM 사용 설명서임시 보안 자격 증명을 참조하세요. 요청 생성에 대한 자세한 내용은 요청 만들기 섹션을 참조하세요.

임시 보안 자격 증명 가져오기 및 Amazon S3에 액세스
  1. AWS Security Token Service 클라이언트의 인스턴스 AmazonSecurityTokenServiceClient를 만듭니다. 자격 증명 제공에 대한 자세한 내용은 AWS SDK 및 Explorer를 사용하여 Amazon S3로 개발 단원을 참조하십시오.

  2. 이전 단계에서 만든 STS 클라이언트의 GetSessionToken 메서드를 호출하여 세션을 시작합니다. GetSessionTokenRequest 객체를 사용하여 이 메서드에 세션 정보를 제공합니다.

    메서드는 임시 보안 자격 증명을 반환합니다.

  3. SessionAWSCredentials 객체의 인스턴스에 임시 보안 자격 증명을 패키지로 포함합니다. 이 객체를 사용하여 Amazon S3 클라이언트에 임시 보안 자격 증명을 제공합니다.

  4. 임시 보안 자격 증명을 전달하여 AmazonS3Client 클래스의 인스턴스를 만듭니다. 이 클라이언트를 사용하여 Amazon S3에 요청을 보냅니다. 만료된 자격 증명을 사용하여 요청을 보낼 경우 Amazon S3에서 오류를 반환합니다.

참고

AWS 계정 보안 자격 증명을 사용하여 획득한 해당 자격 증명의 유효 기간은 1시간입니다. IAM 사용자 자격 증명을 사용하여 세션을 요청할 경우에만 세션 기간을 지정할 수 있습니다.

다음 C# 예제는 지정된 버킷의 객체 키를 나열합니다. 예를 들어, 이 예제에서는 기본 1시간의 세션에 대한 임시 보안 자격 증명을 구한 다음 이 자격 증명을 사용하여 Amazon S3에 인증된 요청을 보냅니다.

IAM 사용자 자격 증명을 사용하여 샘플을 테스트하려면 AWS 계정에서 IAM 사용자를 생성해야 합니다. IAM 사용자를 만드는 방법에 대한 자세한 내용은 IAM 사용 설명서의 첫 번째 IAM 사용자 및 관리자 그룹 생성을 참조하세요. 요청 생성에 대한 자세한 내용은 요청 만들기 섹션을 참조하세요.

실제 예제를 작성 및 테스트하는 방법에 대한 자세한 내용은 Amazon S3 .NET 코드 예제 실행 단원을 참조하십시오.

using Amazon; using Amazon.Runtime; using Amazon.S3; using Amazon.S3.Model; using Amazon.SecurityToken; using Amazon.SecurityToken.Model; using System; using System.Collections.Generic; using System.Threading.Tasks; namespace Amazon.DocSamples.S3 { class TempCredExplicitSessionStartTest { 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 s3Client; public static void Main() { ListObjectsAsync().Wait(); } private static async Task ListObjectsAsync() { try { // Credentials use the default AWS SDK for .NET credential search chain. // On local development machines, this is your default profile. Console.WriteLine("Listing objects stored in a bucket"); SessionAWSCredentials tempCredentials = await GetTemporaryCredentialsAsync(); // Create a client by providing temporary security credentials. using (s3Client = new AmazonS3Client(tempCredentials, bucketRegion)) { var listObjectRequest = new ListObjectsRequest { BucketName = bucketName }; // Send request to Amazon S3. ListObjectsResponse response = await s3Client.ListObjectsAsync(listObjectRequest); List<S3Object> objects = response.S3Objects; Console.WriteLine("Object count = {0}", objects.Count); } } catch (AmazonS3Exception s3Exception) { Console.WriteLine(s3Exception.Message, s3Exception.InnerException); } catch (AmazonSecurityTokenServiceException stsException) { Console.WriteLine(stsException.Message, stsException.InnerException); } } private static async Task<SessionAWSCredentials> GetTemporaryCredentialsAsync() { using (var stsClient = new AmazonSecurityTokenServiceClient()) { var getSessionTokenRequest = new GetSessionTokenRequest { DurationSeconds = 7200 // seconds }; GetSessionTokenResponse sessionTokenResponse = await stsClient.GetSessionTokenAsync(getSessionTokenRequest); Credentials credentials = sessionTokenResponse.Credentials; var sessionCredentials = new SessionAWSCredentials(credentials.AccessKeyId, credentials.SecretAccessKey, credentials.SessionToken); return sessionCredentials; } } } }
PHP

이 예제에서는 이미 AWS SDK for PHP 사용 및 PHP 예제 실행의 지침에 따라 AWS SDK for PHP가 올바르게 설치되어 있다고 가정합니다.

IAM 사용자 또는 AWS 계정은 AWS SDK for PHP 버전 3을 사용하여 임시 보안 자격 증명을 요청할 수 있습니다. 그런 다음 얻은 임시 자격 증명을 사용하여 Amazon S3에 액세스할 수 있습니다. 세션의 유효 기간이 만료되면 이 자격 증명도 만료됩니다.

세션은 기본적으로 1시간 동안 지속됩니다. IAM 사용자 자격 증명을 사용하는 경우, 임시 보안 자격 증명을 요청할 수 있는 기간을 15분에서 역할의 최대 세션 기간까지 지정할 수 있습니다. 임시 보안 자격 증명에 대한 자세한 내용은 IAM 사용 설명서임시 보안 자격 증명을 참조하세요. 요청 생성에 대한 자세한 내용은 요청 만들기 섹션을 참조하세요.

참고

AWS 계정 보안 자격 증명을 사용하여 획득한 임시 보안 자격 증명의 유효 기간은 1시간입니다. IAM 사용자 자격 증명을 사용하여 세션을 요청할 경우에만 세션 기간을 지정할 수 있습니다.

다음 PHP 예제는 임시 보안 자격 증명을 사용하여 지정된 버킷의 객체 키를 나열합니다. 이 예제에서는 기본 1시간의 세션에 대한 임시 보안 자격 증명을 구한 다음 이 자격 증명을 사용하여 Amazon S3에 인증된 요청을 보냅니다. 이 가이드의 PHP 예제 실행에 대한 자세한 내용은 PHP 예제 실행 섹션을 참조하세요.

IAM 사용자 자격 증명을 사용하여 예제를 테스트하려면 AWS 계정에서 IAM 사용자를 생성해야 합니다. IAM 사용자를 만드는 방법에 대한 자세한 내용은 IAM 사용 설명서의 첫 번째 IAM 사용자 및 관리자 그룹 생성을 참조하세요. IAM 사용자의 자격 증명을 사용하여 세션을 요청할 경우 세션 기간을 설정하는 방법에 대한 예제는 IAM 사용자 임시 자격 증명을 사용하여 요청하기 섹션을 참조하세요.

require 'vendor/autoload.php'; use Aws\S3\Exception\S3Exception; use Aws\S3\S3Client; use Aws\Sts\StsClient; $bucket = '*** Your Bucket Name ***'; $sts = new StsClient([ 'version' => 'latest', 'region' => 'us-east-1' ]); $sessionToken = $sts->getSessionToken(); $s3 = new S3Client([ 'region' => 'us-east-1', 'version' => 'latest', 'credentials' => [ 'key' => $sessionToken['Credentials']['AccessKeyId'], 'secret' => $sessionToken['Credentials']['SecretAccessKey'], 'token' => $sessionToken['Credentials']['SessionToken'] ] ]); $result = $s3->listBuckets(); try { // Retrieve a paginator for listing objects. $objects = $s3->getPaginator('ListObjects', [ 'Bucket' => $bucket ]); echo "Keys retrieved!" . PHP_EOL; // List objects foreach ($objects as $object) { echo $object['Key'] . PHP_EOL; } } catch (S3Exception $e) { echo $e->getMessage() . PHP_EOL; }
Ruby

IAM 사용자 또는 AWS 계정은 AWS SDK for Ruby를 사용하여 임시 보안 자격 증명을 요청한 후 이 자격 증명을 사용하여 Amazon S3에 액세스할 수 있습니다. 세션의 유효 기간이 만료된 후 이 자격 증명도 만료됩니다.

세션은 기본적으로 1시간 동안 지속됩니다. IAM 사용자 자격 증명을 사용하는 경우, 임시 보안 자격 증명을 요청할 수 있는 기간을 15분에서 역할의 최대 세션 기간까지 지정할 수 있습니다. 임시 보안 자격 증명에 대한 자세한 내용은 IAM 사용 설명서임시 보안 자격 증명을 참조하세요. 요청 생성에 대한 자세한 내용은 요청 만들기 섹션을 참조하세요.

참고

AWS 계정 보안 자격 증명을 사용하여 획득한 임시 보안 자격 증명의 유효 기간은 1시간입니다. IAM 사용자 자격 증명을 사용하여 세션을 요청할 경우에만 세션 기간을 지정할 수 있습니다.

다음 Ruby 예제는 한 시간 동안 지정된 버킷의 항목을 나열하기 위해 임시 사용자를 생성합니다. 이 예제를 사용하려면 새 AWS Security Token Service(AWS STS) 클라이언트를 생성하고 Amazon S3 버킷을 나열하는데 필요한 권한을 가진 AWS 자격 증명이 있어야 합니다.

# Prerequisites: # - A user in AWS Identity and Access Management (IAM). This user must # be able to assume the following IAM role. You must run this code example # within the context of this user. # - An existing role in IAM that allows all of the Amazon S3 actions for all of the # resources in this code example. This role must also trust the preceding IAM user. # - An existing S3 bucket. require "aws-sdk-core" require "aws-sdk-s3" require "aws-sdk-iam" # Checks whether a user exists in IAM. # # @param iam [Aws::IAM::Client] An initialized IAM client. # @param user_name [String] The user's name. # @return [Boolean] true if the user exists; otherwise, false. # @example # iam_client = Aws::IAM::Client.new(region: 'us-west-2') # exit 1 unless user_exists?(iam_client, 'my-user') def user_exists?(iam_client, user_name) response = iam_client.get_user(user_name: user_name) return true if response.user.user_name rescue Aws::IAM::Errors::NoSuchEntity # User doesn't exist. rescue StandardError => e puts "Error while determining whether the user " \ "'#{user_name}' exists: #{e.message}" end # Creates a user in IAM. # # @param iam_client [Aws::IAM::Client] An initialized IAM client. # @param user_name [String] The user's name. # @return [AWS:IAM::Types::User] The new user. # @example # iam_client = Aws::IAM::Client.new(region: 'us-west-2') # user = create_user(iam_client, 'my-user') # exit 1 unless user.user_name def create_user(iam_client, user_name) response = iam_client.create_user(user_name: user_name) return response.user rescue StandardError => e puts "Error while creating the user '#{user_name}': #{e.message}" end # Gets a user in IAM. # # @param iam_client [Aws::IAM::Client] An initialized IAM client. # @param user_name [String] The user's name. # @return [AWS:IAM::Types::User] The existing user. # @example # iam_client = Aws::IAM::Client.new(region: 'us-west-2') # user = get_user(iam_client, 'my-user') # exit 1 unless user.user_name def get_user(iam_client, user_name) response = iam_client.get_user(user_name: user_name) return response.user rescue StandardError => e puts "Error while getting the user '#{user_name}': #{e.message}" end # Checks whether a role exists in IAM. # # @param iam_client [Aws::IAM::Client] An initialized IAM client. # @param role_name [String] The role's name. # @return [Boolean] true if the role exists; otherwise, false. # @example # iam_client = Aws::IAM::Client.new(region: 'us-west-2') # exit 1 unless role_exists?(iam_client, 'my-role') def role_exists?(iam_client, role_name) response = iam_client.get_role(role_name: role_name) return true if response.role.role_name rescue StandardError => e puts "Error while determining whether the role " \ "'#{role_name}' exists: #{e.message}" end # Gets credentials for a role in IAM. # # @param sts_client [Aws::STS::Client] An initialized AWS STS client. # @param role_arn [String] The role's Amazon Resource Name (ARN). # @param role_session_name [String] A name for this role's session. # @param duration_seconds [Integer] The number of seconds this session is valid. # @return [AWS::AssumeRoleCredentials] The credentials. # @example # sts_client = Aws::STS::Client.new(region: 'us-west-2') # credentials = get_credentials( # sts_client, # 'arn:aws:iam::123456789012:role/AmazonS3ReadOnly', # 'ReadAmazonS3Bucket', # 3600 # ) # exit 1 if credentials.nil? def get_credentials(sts_client, role_arn, role_session_name, duration_seconds) Aws::AssumeRoleCredentials.new( client: sts_client, role_arn: role_arn, role_session_name: role_session_name, duration_seconds: duration_seconds ) rescue StandardError => e puts "Error while getting credentials: #{e.message}" end # Checks whether a bucket exists in Amazon S3. # # @param s3_client [Aws::S3::Client] An initialized Amazon S3 client. # @param bucket_name [String] The name of the bucket. # @return [Boolean] true if the bucket exists; otherwise, false. # @example # s3_client = Aws::S3::Client.new(region: 'us-west-2') # exit 1 unless bucket_exists?(s3_client, 'doc-example-bucket') def bucket_exists?(s3_client, bucket_name) response = s3_client.list_buckets response.buckets.each do |bucket| return true if bucket.name == bucket_name end rescue StandardError => e puts "Error while checking whether the bucket '#{bucket_name}' " \ "exists: #{e.message}" end # Lists the keys and ETags for the objects in an Amazon S3 bucket. # # @param s3_client [Aws::S3::Client] An initialized Amazon S3 client. # @param bucket_name [String] The bucket's name. # @return [Boolean] true if the objects were listed; otherwise, false. # @example # s3_client = Aws::S3::Client.new(region: 'us-west-2') # exit 1 unless list_objects_in_bucket?(s3_client, 'doc-example-bucket') def list_objects_in_bucket?(s3_client, bucket_name) puts "Accessing the contents of the bucket named '#{bucket_name}'..." response = s3_client.list_objects_v2( bucket: bucket_name, max_keys: 50 ) if response.count.positive? puts "Contents of the bucket named '#{bucket_name}' (first 50 objects):" puts "Name => ETag" response.contents.each do |obj| puts "#{obj.key} => #{obj.etag}" end else puts "No objects in the bucket named '#{bucket_name}'." end return true rescue StandardError => e puts "Error while accessing the bucket named '#{bucket_name}': #{e.message}" end

관련 리소스