8

为了向 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 消息传递和自动配置做同样的事情,但到目前为止我还没有找到任何关于该主题的信息。我的application.yml看起来像这样

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

Spring 是否支持它,而我只是没有设法找到它,还是应该坚持使用 AWS SDK?

4

1 回答 1

3

看起来没有开箱即用的解决方案。最简单的解决方法是创建您自己的 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();
    }
}
于 2018-02-15T07:41:41.060 回答