An IAM user or an AWS Account can request temporary security credentials (see Making Requests) using the 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.

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.

Copy

// 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(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);

Note

If you obtain temporary security credentials using your AWS account security 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.