- Java
-
An IAM user or an AWS account can request temporary security credentials
(see Making requests) using the
AWS SDK for Java and use them to access Amazon S3. These credentials expire after the
specified session duration.
By default, the session duration is one hour. If you use IAM user
credentials, you can specify the duration when requesting the temporary security
credentials from 15 minutes to the maximum session duration for the role. For
more information about temporary security credentials, see Temporary Security
Credentials in the IAM User Guide. For more
information about making requests, see Making requests.
To get temporary security credentials and access Amazon S3
-
Create an instance of the AWSSecurityTokenService
class.
-
Retrieve the temporary security credentials for the desired role by
calling the assumeRole()
method of the Security Token
Service (STS) client.
-
Package the temporary security credentials into a
BasicSessionCredentials
object. You use this object to
provide the temporary security credentials to your Amazon S3 client.
-
Create an instance of the AmazonS3Client
class using the
temporary security credentials. You send requests to Amazon S3 using this
client. If you send requests using expired credentials, Amazon S3 will return
an error.
The following example lists a set of object keys in the specified bucket. The
example obtains temporary security credentials for a session and uses them to
send an authenticated request to Amazon S3.
If you want to test the sample by using IAM user credentials, you must create an
IAM user under your AWS account. For more information about how to create an
IAM user, see Creating Your
First IAM user and Administrators Group in the
IAM User Guide.
For instructions on creating and testing a working sample, see Getting
Started in the AWS SDK for Java Developer Guide.
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 {
AWSSecurityTokenService stsClient = AWSSecurityTokenServiceClientBuilder.standard()
.withCredentials(new ProfileCredentialsProvider())
.withRegion(clientRegion)
.build();
AssumeRoleRequest roleRequest = new AssumeRoleRequest()
.withRoleArn(roleARN)
.withRoleSessionName(roleSessionName);
AssumeRoleResult roleResponse = stsClient.assumeRole(roleRequest);
Credentials sessionCredentials = roleResponse.getCredentials();
BasicSessionCredentials awsCredentials = new BasicSessionCredentials(
sessionCredentials.getAccessKeyId(),
sessionCredentials.getSecretAccessKey(),
sessionCredentials.getSessionToken());
AmazonS3 s3Client = AmazonS3ClientBuilder.standard()
.withCredentials(new AWSStaticCredentialsProvider(awsCredentials))
.withRegion(clientRegion)
.build();
ObjectListing objects = s3Client.listObjects(bucketName);
System.out.println("No. of Objects: " + objects.getObjectSummaries().size());
} catch (AmazonServiceException e) {
e.printStackTrace();
} catch (SdkClientException e) {
e.printStackTrace();
}
}
}
- .NET
-
An IAM user or an AWS account can request temporary security credentials
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 the duration when requesting the temporary security
credentials from 15 minutes to the maximum session duration for the role. For
more information about temporary security credentials, see Temporary Security
Credentials in the IAM User Guide. For more
information about making requests, see Making requests.
To get temporary security credentials and access Amazon S3
-
Create an instance of the AWS Security Token Service client,
AmazonSecurityTokenServiceClient
.
-
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 your temporary security credentials.
-
Package 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.
-
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# example lists object keys in the specified bucket. For
illustration, the 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 by using IAM user credentials, you must create an
IAM user under your AWS account. For more information about how to create an
IAM user, see Creating Your
First IAM user and Administrators Group in the
IAM User Guide. For more information about making
requests, see Making requests.
For
information about setting up and running the code examples, see Getting Started
with the AWS SDK for .NET in the AWS SDK for .NET Developer
Guide.
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 ***";
private static readonly RegionEndpoint bucketRegion = RegionEndpoint.USWest2;
private static IAmazonS3 s3Client;
public static void Main()
{
ListObjectsAsync().Wait();
}
private static async Task ListObjectsAsync()
{
try
{
Console.WriteLine("Listing objects stored in a bucket");
SessionAWSCredentials tempCredentials = await GetTemporaryCredentialsAsync();
using (s3Client = new AmazonS3Client(tempCredentials, bucketRegion))
{
var listObjectRequest = new ListObjectsRequest
{
BucketName = bucketName
};
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
};
GetSessionTokenResponse sessionTokenResponse =
await stsClient.GetSessionTokenAsync(getSessionTokenRequest);
Credentials credentials = sessionTokenResponse.Credentials;
var sessionCredentials =
new SessionAWSCredentials(credentials.AccessKeyId,
credentials.SecretAccessKey,
credentials.SessionToken);
return sessionCredentials;
}
}
}
}
- PHP
-
For more information about the AWS SDK for Ruby API, go to AWS SDK for Ruby - Version
2.
An IAM user or an AWS account can request temporary security credentials
using version 3 of the AWS SDK for PHP. It can then use the temporary credentials to
access Amazon S3. The credentials expire when the session duration expires.
By default, the session duration is one hour. If you use IAM user
credentials, you can specify the duration when requesting the temporary security
credentials from 15 minutes to the maximum session duration for the role. For
more information about temporary security credentials, see Temporary Security
Credentials in the IAM User Guide. For more
information about making requests, see Making requests.
The following PHP example lists object keys in the specified bucket using
temporary security credentials. The example obtains temporary security
credentials for a default one-hour session, and uses them to send
authenticated request to Amazon S3. For more information about the AWS SDK for Ruby API, go to AWS SDK for Ruby - Version
2.
If you want to test the example by using IAM user credentials, you must create an
IAM user under your AWS account. For information about how to create an
IAM user, see Creating
Your First IAM user and Administrators Group in the
IAM User Guide. For examples of setting the
session duration when using IAM user credentials to request a session, see
Making requests using IAM user temporary
credentials .
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 {
$objects = $s3->getPaginator('ListObjects', [
'Bucket' => $bucket
]);
echo "Keys retrieved!" . PHP_EOL;
foreach ($objects as $object) {
echo $object['Key'] . PHP_EOL;
}
} catch (S3Exception $e) {
echo $e->getMessage() . PHP_EOL;
}
- Ruby
-
An IAM user or an AWS account can request temporary security credentials
using AWS SDK for Ruby 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 the duration when requesting the temporary security
credentials from 15 minutes to the maximum session duration for the role. For
more information about temporary security credentials, see Temporary Security
Credentials in the IAM User Guide. For more
information about making requests, see Making requests.
The following Ruby example creates a temporary user to list the items in a
specified bucket for one hour. To use this example, you must have AWS
credentials that have the necessary permissions to create new AWS Security Token Service (AWS STS)
clients, and list Amazon S3 buckets.
require 'aws-sdk-core'
require 'aws-sdk-s3'
require 'aws-sdk-iam'
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
rescue StandardError => e
puts 'Error while determining whether the user ' \
"'#{user_name}' exists: #{e.message}"
end
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
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
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
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
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
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