How to Configure using STSAssumeRoleSessionCredentialsProvider with roleSessionName and roleArn for AWS SDK for Java 2.x?

Viewed 3419

Currently for AWS SDK for Java 1.x im using below code.

@Configuration
@ImportResource("classpath:aws-context.xml")
public class AmazonS3Config {
 @Bean(destroyMethod = "shutdown")
 public AmazonS3Client amazonS3Client(@Value("${aws.s3.roleSessionName}") String roleSessionName, 
 @Value("${aws.s3.roleArn}") String role) {
 AmazonS3ClientBuilder builder = AmazonS3ClientBuilder.standard();
 builder.withRegion(Regions.US_EAST_1).withCredentials(new 
 STSAssumeRoleSessionCredentialsProvider.Builder(role, roleSessionName).build());
 return (AmazonS3Client)builder.build();
   }

How to do the same for AWS SDK for Java 2.x?

Thanks

2 Answers

The equivalent of STSAssumeRoleSessionCredentialsProvider in SDK V2 is StsAssumeRoleCredentialsProvider.

So the equivalent S3Client initialisation in V2 would look like below

public S3Client s3Client(@Value("${aws.s3.roleSessionName}") String roleSessionName,  
        @Value("${aws.s3.roleArn}") String role) {

 return S3Client
       .builder()
       .region(Region.US_EAST_1)
       .credentialsProvider(StsAssumeRoleCredentialsProvider
               .builder()
               .refreshRequest(() -> AssumeRoleRequest
                       .builder()
                       .roleArn(role)
                       .roleSessionName(roleSessionName)
                       .build())
               .build())
       .build();

The maven/gradle dependency group and the package names have changed to software.amazon.awssdk in V2. Ensure to include the dependencies for S3 and STS. Here is the change log and here is the migration guide.

Related