

# IAM ユーザーの一時的な認証情報を使用したリクエストの実行
<a name="AuthUsingTempSessionToken"></a>

 AWS アカウント または IAM ユーザーは、一時的なセキュリティ認証情報をリクエストし、そのセキュリティ認証情報を使用して、認証リクエストを Amazon S3 に送信できます。このセクションでは、AWS SDK for Java、.NET、および PHP を使用して一時セキュリティ認証情報を取得する方法と、Amazon S3 に対するリクエストの認証にその認証情報を使用する方法について説明します。

------
#### [ Java ]

IAM ユーザーまたは AWS アカウント は、AWS SDK for Java を使用して一時的なセキュリティ認証情報をリクエストし ([リクエストの実行](MakingRequests.md) を参照)、その認証情報を使用して Amazon S3 にアクセスできます。これらの認証情報は、指定したセッションの有効期間が過ぎると失効します。

デフォルトでは、セッションの有効期間は 1 時間です。IAM ユーザーの認証情報を使用する場合、一時的なセキュリティ認証情報をリクエストする期間を 15 分からロールの最大セッション期間までで指定できます。一時的なセキュリティ認証情報の詳細については、[IAM ユーザーガイド](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp.html)の「*IAM の一時的なセキュリティ認証情報*」を参照してください。リクエストの実行の詳細については、「[リクエストの実行](MakingRequests.md)」を参照してください。

**一時的なセキュリティ認証情報を取得して Amazon S3 にアクセスするには**

1. `AWSSecurityTokenService` クラスのインスタンスを作成します。

1. Security Token Service (STS) クライアントの `assumeRole()` メソッドを呼び出して、該当ロールの一時的なセキュリティ認証情報を取得します。

1. 一時的なセキュリティ認証情報を `BasicSessionCredentials` オブジェクトにパッケージ化します。このオブジェクトを使用して、一時的なセキュリティ認証情報を Amazon S3 クライアントに提供します。

1. 一時的なセキュリティ認証情報を使用して、`AmazonS3Client` クラスのインスタンスを作成します。このクライアントを使用してリクエストを Amazon S3 に送信します。失効した認証情報を使用してリクエストを送信すると、Amazon S3 はエラーを返します。

**注記**  
AWS アカウント のセキュリティ認証情報を使用して一時的なセキュリティ認証情報を取得した場合、この認証情報は 1 時間だけ有効です。セッションの有効期間を指定できるのは、セッションのリクエストに IAM ユーザー証明書を使用する場合のみです。

次の例では、指定したバケット内のオブジェクトキーを一覧表示します。この例では、セッションの一時的なセキュリティ認証情報を取得し、これを使用して認証済みのリクエストを Amazon S3 に送信します。

IAM ユーザーの認証情報を使用してサンプルをテストする場合は、AWS アカウントで IAM ユーザーを作成する必要があります。IAM ユーザーを作成する方法の詳細については、「*IAM ユーザーガイド*」の「[最初の IAM ユーザーおよび管理者グループの作成](https://docs.aws.amazon.com/IAM/latest/UserGuide/getting-started_create-admin-group.html)」を参照してください。

作業サンプルの作成およびテストの手順については、「AWS SDK for Java のデベロッパーガイド」の「[使用開始](https://docs.aws.amazon.com/sdk-for-java/v1/developer-guide/getting-started.html)」を参照してください。

```
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 ユーザーガイド](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp.html)の「*IAM の一時的なセキュリティ認証情報*」を参照してください。リクエストの実行の詳細については、「[リクエストの実行](MakingRequests.md)」を参照してください。

**一時的なセキュリティ認証情報を取得して Amazon S3 にアクセスするには**

1. AWS Security Token Service クライアント `AmazonSecurityTokenServiceClient` のインスタンスを作成します。

1. 前の手順で作成した STS クライアントの `GetSessionToken` メソッドを呼び出して、セッションを開始します。`GetSessionTokenRequest` オブジェクトを使用して、このメソッドにセッション情報を指定します。

   このメソッドは一時的なセキュリティ認証情報を返します。

1. `SessionAWSCredentials` オブジェクトのインスタンスに一時セキュリティ証明書をパッケージ化します。このオブジェクトを使用して、一時的なセキュリティ認証情報を Amazon S3 クライアントに提供します。

1. 一時セキュリティ証明書を渡して、`AmazonS3Client` クラスのインスタンスを作成します。このクライアントを使用してリクエストを Amazon S3 に送信します。失効した認証情報を使用してリクエストを送信すると、Amazon S3 はエラーを返します。

**注記**  
AWS アカウント のセキュリティ認証情報を使用して一時的なセキュリティ認証情報を取得した場合、この認証情報は 1 時間だけ有効です。セッションの有効期間を指定できるのは、IAM ユーザーの認証情報を使用してセッションをリクエストする場合に限ります。

次の C\# の例では、指定したバケットのオブジェクトキーを一覧表示します。この例では、わかりやすいように、デフォルトの 1 時間のセッションの一時セキュリティ認証情報を取得し、それを使用して認証リクエストを Amazon S3 に送信しています。

IAM ユーザーの認証情報を使用してサンプルをテストする場合は、AWS アカウントで IAM ユーザーを作成する必要があります。IAM ユーザーを作成する方法の詳細については、「*IAM ユーザーガイド*」の「[最初の IAM ユーザーおよび管理者グループの作成](https://docs.aws.amazon.com/IAM/latest/UserGuide/getting-started_create-admin-group.html)」を参照してください。リクエストの実行の詳細については、「[リクエストの実行](MakingRequests.md)」を参照してください。

 コード例を設定および実行する方法の詳細については、「*AWS SDK for .NET デベロッパーガイド*」の「[AWS SDK for .NET の開始方法](https://docs.aws.amazon.com/sdk-for-net/latest/developer-guide/net-dg-setup.html)」 を参照してください。

```
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 Ruby API の詳細については、[AWS SDK for Ruby - バージョン 2](https://docs.aws.amazon.com/sdkforruby/api/index.html) を参照してください。

IAM ユーザーまたは AWS アカウント は、バージョン 3 の AWS SDK for PHP を使用して一時的なセキュリティ認証情報をリクエストできます。次に、この一時的な認証情報を使用して Amazon S3 にアクセスできます。認証情報は、セッションの有効期間が失効すると同時に失効します。

デフォルトでは、セッションの有効期間は 1 時間です。IAM ユーザーの認証情報を使用する場合、一時的なセキュリティ認証情報をリクエストする期間を 15 分からロールの最大セッション期間までで指定できます。一時的なセキュリティ認証情報の詳細については、[IAM ユーザーガイド](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp.html)の「*IAM の一時的なセキュリティ認証情報*」を参照してください。リクエストの実行の詳細については、「[リクエストの実行](MakingRequests.md)」を参照してください。

**注記**  
AWS アカウント のセキュリティ認証情報を使用して一時的なセキュリティ認証情報を取得する場合、取得した一時的なセキュリティ認証情報は 1 時間だけ有効です。セッションの有効期間を指定できるのは、セッションのリクエストに IAM ユーザー証明書を使用する場合のみです。

**Example**  
次の PHP の例では、一時的なセキュリティ認証情報を使用して、指定したバケットのオブジェクトキーを一覧表示します。この例では、一時的なセキュリティ認証情報をデフォルトの 1 時間のセッションとして取得し、それを使用して認証済みのリクエストを Amazon S3 に送信します。AWS SDK for Ruby API の詳細については、[AWS SDK for Ruby - バージョン 2](https://docs.aws.amazon.com/sdkforruby/api/index.html) を参照してください。  
IAM ユーザーの認証情報を使用して例をテストする場合は、AWS アカウントで IAM ユーザーを作成する必要があります。IAM ユーザーを作成する方法については、「*IAM ユーザーガイド*」の「[最初の IAM ユーザーおよび管理者グループの作成](https://docs.aws.amazon.com/IAM/latest/UserGuide/getting-started_create-admin-group.html)」を参照してください。IAM ユーザーの認証情報を使用してセッションをリクエストするときにセッションの有効期間を設定する例については、「[IAM ユーザーの一時的な認証情報を使用したリクエストの実行](#AuthUsingTempSessionToken)」を参照してください。  

```
 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 ユーザーガイド](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp.html)の「*IAM の一時的なセキュリティ認証情報*」を参照してください。リクエストの実行の詳細については、「[リクエストの実行](MakingRequests.md)」を参照してください。

**注記**  
AWS アカウント のセキュリティ認証情報を使用して一時的なセキュリティ認証情報を取得する場合、取得した一時的なセキュリティ認証情報は 1 時間だけ有効です。セッションの有効期間を指定できるのは、セッションのリクエストに IAM ユーザー認証情報を使用する場合のみです。

次の Ruby の例では、有効期間が 1 時間の一時的なユーザーを作成し、指定したバケットの項目を一覧表示します。この例を使用するには、新しい 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)
  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)
  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, 'amzn-s3-demo-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, 'amzn-s3-demo-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
  true
rescue StandardError => e
  puts "Error while accessing the bucket named '#{bucket_name}': #{e.message}"
end
```

------