使用Spring Cloud AWS自动配置扮演角色

9
为了向SNS发布消息,我需要扮演正确的角色。因此,在使用AWS SDK时,我会创建一个名为AmazonSNS的bean,如下所示:
@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();
}

我正在尝试使用Spring Cloud AWS Messaging & Autoconfiguration实现同样的功能,但到目前为止,我还没有找到任何相关信息。我的application.yml文件如下:

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

这个功能在Spring中是否有支持,我只是没有找到呢?还是应该继续使用AWS SDK?

1个回答

4

看起来没有现成的解决方案。最简单的变通方法是创建自己的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();
    }
}

扮演的角色理想情况下应该在一定时间后过期。这个自动处理了吗? - The Cloud Guy
1
只是想就处理STS会话短超时的问题发表一下意见。STSAssumeRoleSessionCredentialsProvider有一个在后台刷新会话的机制。 - marcus.ramsden

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接