use of software.amazon.awssdk.services.sts.model.Credentials in project aws-doc-sdk-examples by awsdocs.
the class IAMScenario method assumeGivenRole.
// Invoke an Amazon S3 operation using the Assumed Role.
public static void assumeGivenRole(String roleArn, String roleSessionName, String bucketName) {
StsClient stsClient = StsClient.builder().region(Region.US_EAST_1).build();
try {
AssumeRoleRequest roleRequest = AssumeRoleRequest.builder().roleArn(roleArn).roleSessionName(roleSessionName).build();
AssumeRoleResponse roleResponse = stsClient.assumeRole(roleRequest);
Credentials myCreds = roleResponse.credentials();
String key = myCreds.accessKeyId();
String secKey = myCreds.secretAccessKey();
String secToken = myCreds.sessionToken();
// List all objects in an Amazon S3 bucket using the temp creds.
Region region = Region.US_EAST_1;
S3Client s3 = S3Client.builder().credentialsProvider(StaticCredentialsProvider.create(AwsSessionCredentials.create(key, secKey, secToken))).region(region).build();
System.out.println("Created a S3Client using temp credentials.");
System.out.println("Listing objects in " + bucketName);
ListObjectsRequest listObjects = ListObjectsRequest.builder().bucket(bucketName).build();
ListObjectsResponse res = s3.listObjects(listObjects);
List<S3Object> objects = res.contents();
for (S3Object myValue : objects) {
System.out.println("The name of the key is " + myValue.key());
System.out.println("The owner is " + myValue.owner());
}
} catch (StsException e) {
System.err.println(e.getMessage());
System.exit(1);
}
}
use of software.amazon.awssdk.services.sts.model.Credentials in project aws-doc-sdk-examples by awsdocs.
the class AssumeRole method assumeGivenRole.
// snippet-start:[sts.java2.assume_role.main]
public static void assumeGivenRole(StsClient stsClient, String roleArn, String roleSessionName) {
try {
AssumeRoleRequest roleRequest = AssumeRoleRequest.builder().roleArn(roleArn).roleSessionName(roleSessionName).build();
AssumeRoleResponse roleResponse = stsClient.assumeRole(roleRequest);
Credentials myCreds = roleResponse.credentials();
// Display the time when the temp creds expire
Instant exTime = myCreds.expiration();
String tokenInfo = myCreds.sessionToken();
// Convert the Instant to readable date
DateTimeFormatter formatter = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.SHORT).withLocale(Locale.US).withZone(ZoneId.systemDefault());
formatter.format(exTime);
System.out.println("The token " + tokenInfo + " expires on " + exTime);
} catch (StsException e) {
System.err.println(e.getMessage());
System.exit(1);
}
}
Aggregations