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

There are 2 answers

0
GSSwain On

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.

0
smac2020 On

TO learn how to return a set of temporary security credentials using the V2 StsClient, look at this example:

https://github.com/awsdocs/aws-doc-sdk-examples/blob/master/javav2/example_code/sts/src/main/java/com/example/sts/AssumeRole.java

You can find the corresponding POM file here:

https://github.com/awsdocs/aws-doc-sdk-examples/tree/master/javav2/example_code/sts

All Java V2 Service code examples are located here:

https://github.com/awsdocs/aws-doc-sdk-examples/tree/master/javav2

Java V2 DEV Guide is here - https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/home.html