amazon-web-servicesamazon-s3amazon-iamaws-java-sdk-2.xaws-iam-roles-anywhere

How to programmatically create IAM Roles Anywhere sessions with AWS SDK for Java V2 in a Spring Boot service


I'm working on a Spring Boot backend service where I need to access certain S3 buckets programmatically using IAM Roles Anywhere. I found the following documentation for RolesAnywhereClient in the AWS SDK for Java V2:

https://sdk.amazonaws.com/java/api/latest/software/amazon/awssdk/services/rolesanywhere/RolesAnywhereClient.html

However, I’m unsure how to use it to create IAM Roles Anywhere sessions and authenticate to access S3.

I have all credentials needed for IAM roles anywhere: profile-arn, trust-anchor-arn, role-arn, certificate and private key. How to programmatically create IAM Roles Anywhere sessions with AWS SDK for Java V2 in a Spring Boot service to access S3 buckets?


Solution

  • As a quick way to create a session and get temporary creds, you can leverage the credential helper tool.

    After you get all the pieces assembled locally and you get the helper tool working from the command line to return temp creds, you can add the command to the ~/.aws/config file:

    [profile roles_anywhere]
        credential_process = ./aws_signing_helper credential-process --certificate /path/to/certificate --private-key /path/to/private-key --trust-anchor-arn arn:aws:rolesanywhere:region:account:trust-anchor/TA_ID --profile-arn arn:aws:rolesanywhere:region:account:profile/PROFILE_ID --role-arn arn:aws:iam::account:role/role-name-with-path
    

    Then in Java:

    ProfileCredentialsProvider profileCredentialsProvider =  
                ProfileCredentialsProvider.builder()
                        .profileName("roles_anywhere")
                        .build();
     s3Client = S3Client.builder()
                      .credentialsProvider(profileCredentialsProvider)
                      .build();
    

    Or use a ProcessCredentialsProvider if you want to do it all in code:

                    ProcessCredentialsProvider processCredentialsProvider = ProcessCredentialsProvider.builder()
                        .command("""
                                ./aws_signing_helper credential-process \
                                --certificate /path/to/certificate \
                                --private-key /path/to/private-key \
                                --trust-anchor-arn arn:aws:rolesanywhere:region:account:trust-anchor/TA_ID \
                                --profile-arn arn:aws:rolesanywhere:region:account:profile/PROFILE_ID \
                                --role-arn arn:aws:iam::account:role/role-name-with-path
                            """).build();
    
    
                    s3Client = S3Client.builder()//.create();
                      .credentialsProvider(processCredentialsProvider)
                      .build();