Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
A way to make requests to AWS that require assuming a role when using V1 of the AWS Java SDK.
package com.joelforjava.aws.assumerole.example;
import com.amazonaws.auth.AWSCredentialsProvider;
import com.amazonaws.auth.AWSStaticCredentialsProvider;
import com.amazonaws.auth.BasicSessionCredentials;
import com.amazonaws.auth.DefaultAWSCredentialsProviderChain;
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.AWSSecurityTokenServiceAsyncClientBuilder;
import com.amazonaws.services.securitytoken.model.AssumeRoleRequest;
import com.amazonaws.services.securitytoken.model.AssumeRoleResult;
import com.amazonaws.services.securitytoken.model.Credentials;
public class MakingAssumeRoleRequests {
private static AWSCredentialsProvider loadCredentials(boolean isLocal) {
final AWSCredentialsProvider credentialsProvider;
if (isLocal) {
AWSSecurityTokenService stsClient = AWSSecurityTokenServiceAsyncClientBuilder.standard()
.withCredentials(new ProfileCredentialsProvider("devjump"))
.withRegion("us-east-1")
.build();
AssumeRoleRequest assumeRoleRequest = new AssumeRoleRequest().withDurationSeconds(3600)
.withRoleArn("arn:aws:iam::1234567890987:role/Super-Important-Role")
.withRoleSessionName("S3_Session");
AssumeRoleResult assumeRoleResult = stsClient.assumeRole(assumeRoleRequest);
Credentials creds = assumeRoleResult.getCredentials();
credentialsProvider = new AWSStaticCredentialsProvider(
new BasicSessionCredentials(creds.getAccessKeyId(),
creds.getSecretAccessKey(),
creds.getSessionToken())
);
} else {
credentialsProvider = new DefaultAWSCredentialsProviderChain();
}
return credentialsProvider;
}
public static void main(String[] args) {
AWSCredentialsProvider credentialsProvider = loadCredentials(true);
AmazonS3 s3Client = AmazonS3ClientBuilder.standard()
.withCredentials(credentialsProvider)
.withRegion("us-east-1")
.build();
ObjectListing objects = s3Client.listObjects("bucket-name");
System.out.printf("No. of Objects: %s", objects.getObjectSummaries().size());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment