Amazon Simple Storage Service
Developer Guide (API Version 2006-03-01)
Print this pageEmail this pageGo to the ForumsView the PDFShare this page on TwitterShare this page on FacebookBookmark this page on DeliciousSubmit this page to RedditSubmit this page to DiggDid this page help you?  Yes  No   Tell us about it...

Making Requests Using IAM User Temporary Credentials - AWS SDK for .NET

An IAM user or an AWS Account can request temporary security credentials (see Making Requests) using AWS SDK for .NET and use them to access Amazon S3. These credentials expire after the session duration. By default, the session duration is one hour. If you use IAM user credentials, you can specify duration, between 1 and 36 hours, when requesting the temporary security credentials.

Making Requests Using IAM User Temporary Security Credentials

1

Create an instance of the AWS Security Token Service client AmazonSecurityTokenServiceClient by providing your credentials.

2

Start a session by calling the GetSessionToken method of the STS client you created in the preceding step. You provide session information to this method using a GetSessionTokenRequest object.

The method returns you temporary security credentials.

3

Package up the temporary security credentials in an instance of the SessionAWSCredentials object. You use this object to provide the temporary security credentials to your Amazon S3 client.

4

Create an instance of the AmazonS3Client class by passing in the temporary security credentials.

You send requests to Amazon S3 using this client. If you send requests using expired credentials, Amazon S3 returns an error.


The following C# code sample demonstrates the preceding tasks.

// In real applications, the following code is part of your trusted code. It has 
// your security credentials you use to obtain temporary security credentials.
AmazonSecurityTokenServiceConfig config = new AmazonSecurityTokenServiceConfig();
 AmazonSecurityTokenServiceClient stsClient = 
           new AmazonSecurityTokenServiceClient("*** Access Key ID ***", 
                                                "*** Secret Access Key ***", 
                                                config);

GetSessionTokenRequest getSessionTokenRequest = new GetSessionTokenRequest();
// Following duration can be set only if temporary credentials are requested by an IAM user.
getSessionTokenRequest.DurationSeconds = 7200; // seconds.
Credentials credentials = 
     stsClient.GetSessionToken(getSessionTokenRequest).GetSessionTokenResult.Credentials;

SessionAWSCredentials sessionCredentials = 
                          new SessionAWSCredentials(credentials.AccessKeyId,
                                                    credentials.SecretAccessKey,
                                                    credentials.SessionToken);

// The following will be part of your less trusted code. You provide temporary security
// credentials so it can send authenticated requests to Amazon S3. 
// Create Amazon S3 client by passing in the basicSessionCredentials object.
AmazonS3Client s3Client = new AmazonS3Client(sessionCredentials); 

// Test. For example, send request to list object key in a bucket.
var response = s3Client.ListObjects(bucketName);

Example

[Note]Note

If you obtain temporary security credentials using your AWS account credentials, the temporary security credentials are valid for only one hour. You can specify session duration only if you use IAM user credentials to request a session.

The following C# code example lists object keys in the specified bucket. For illustration, the code example obtains temporary security credentials for a default one hour session and uses them to send authenticated request to Amazon S3.

If you want to test the sample using IAM user credentials, you will need to create an IAM user under your AWS Account. For more information about how to create an IAM user, go to Set Up a Group, Grant Permissions, and Add Users in the AWS Identity and Access Management Getting Started Guide.

using System;
using System.Configuration;
using System.Collections.Specialized;
using Amazon.S3;
using Amazon.SecurityToken;
using Amazon.SecurityToken.Model;
using Amazon.Runtime;
using Amazon.S3.Model;
using System.Collections.Generic;

namespace s3.amazon.com.docsamples.listingkeys
{
    class TempCred_ExplicitSessionStart
    {
        static string bucketName = "*** Provide bucket name ***"; 
        static AmazonS3 client;

        public static void Main(string[] args)
        {
            NameValueCollection appConfig = ConfigurationManager.AppSettings;
            string accessKeyID = appConfig["AWSAccessKey"];
            string secretAccessKeyID = appConfig["AWSSecretKey"];
            try
            {
                Console.WriteLine("Listing objects stored in a bucket");
                SessionAWSCredentials tempCredentials =
                     GetTemporaryCredentials(accessKeyID, secretAccessKeyID);

                // Create client by providing temporary security credentials.
                AmazonS3Client s3Client = new AmazonS3Client(tempCredentials);

                ListObjectsRequest listObjectRequest =
                                  new ListObjectsRequest();
                listObjectRequest.BucketName = bucketName;

                // Send request to Amazon S3.
                ListObjectsResponse response = s3Client.ListObjects(listObjectRequest);
                List<S3Object> objects = response.S3Objects;
                Console.WriteLine("Object count = {0}", objects.Count);

                Console.WriteLine("Press any key to continue...");
                Console.ReadKey();
            }
            catch (AmazonS3Exception s3Exception)
            {
                Console.WriteLine(s3Exception.Message,
                                  s3Exception.InnerException);
            }
            catch (AmazonSecurityTokenServiceException stsException)
            {
                Console.WriteLine(stsException.Message,
                                 stsException.InnerException);
            }
        }

        private static SessionAWSCredentials GetTemporaryCredentials(
                         string accessKeyId, string secretAccessKeyId)
        {
            AmazonSecurityTokenServiceClient stsClient =
                new AmazonSecurityTokenServiceClient(accessKeyId,
                                                     secretAccessKeyId); 

            GetSessionTokenRequest getSessionTokenRequest = 
                                             new GetSessionTokenRequest();
            getSessionTokenRequest.DurationSeconds = 7200; // seconds

            GetSessionTokenResponse sessionTokenResponse = 
                          stsClient.GetSessionToken(getSessionTokenRequest);
            GetSessionTokenResult sessionTokenResult = 
                                   sessionTokenResponse.GetSessionTokenResult;
            Credentials credentials = sessionTokenResult.Credentials;

            SessionAWSCredentials sessionCredentials =
       SessionAWSCredentials.CreateStaticCredentials(credentials.AccessKeyId,
                                                     credentials.SecretAccessKey,
                                                     credentials.SessionToken);

            return sessionCredentials;
        }
    }
}