9

In order to publish messages to SNS I need to assume the correct role, so when using AWS SDK I create an AmazonSNS bean like this:

@Bean
public AmazonSNS amazonSnsClient(
        @Value("${cloud.aws.credentials.accessKey}") String accessKey,
        @Value("${cloud.aws.credentials.secretKey}") String secretKey,
        @Value("${cloud.aws.role.publisherArn}") String publisherRoleArn
) {
    AWSSecurityTokenService stsClient = AWSSecurityTokenServiceClientBuilder.standard()
            .withRegion(EU_CENTRAL_1)
            .withCredentials(new AWSStaticCredentialsProvider(new BasicAWSCredentials(accessKey, secretKey)))
            .build();
    STSAssumeRoleSessionCredentialsProvider credentialsProvider = new STSAssumeRoleSessionCredentialsProvider
            .Builder(publisherRoleArn, SESSION_NAME)
            .withStsClient(stsClient)
            .build();
    return AmazonSNSClientBuilder.standard()
            .withRegion(EU_CENTRAL_1)
            .withCredentials(credentialsProvider)
            .build();
}

I'm trying to do the same with Spring Cloud AWS Messaging & Autoconfiguration but so far I didn't find any info on the topic. My application.yml looks like this

cloud:   
    aws:
        credentials:
            accessKey: ***
            secretKey: ***
            instanceProfile: true
        region:
            static: eu-central-1

Is it supported by Spring and I just didn't manage to find it or should I just stick to AWS SDK?

Maciej
  • 546
  • 4
  • 15

1 Answers1

4

Looks like there is no out-of-the-box solution for that. The easiest workaround is to create your own AWSCredentialsProvider bean

@Configuration
public class AwsCredentials {

    private static final String SESSION_NAME = "TestConsumer";

    @Bean
    @Primary
    public AWSCredentialsProvider credentialsProvider(
            @Value("${cloud.aws.credentials.accessKey}") String accessKey,
            @Value("${cloud.aws.credentials.secretKey}") String secretKey,
            @Value("${cloud.aws.role}") String role ) {

        AWSSecurityTokenService stsClient = AWSSecurityTokenServiceClientBuilder.standard()
            .withRegion(EU_CENTRAL_1)
            .withCredentials(new AWSStaticCredentialsProvider(new BasicAWSCredentials(accessKey, secretKey)))
            .build();
        return new STSAssumeRoleSessionCredentialsProvider
            .Builder(role, SESSION_NAME)
            .withStsClient(stsClient)
            .build();
    }
}
Maciej
  • 546
  • 4
  • 15
  • assumed role ideally expires after a certain time. Is this taken care of automatically? – The Cloud Guy Jan 18 '20 at 07:03
  • 1
    Just to chime in on the question of dealing with the short timeout of STS sessions. [STSAssumeRoleSessionCredentialsProvider](https://docs.aws.amazon.com/AWSJavaSDK/latest/javadoc/com/amazonaws/auth/STSAssumeRoleSessionCredentialsProvider.html) has a mechanism for refreshing sessions in the background. – marcus.ramsden Aug 15 '22 at 09:04