Spring Boot 如何在java代码中使用DefaultAWSCredentialsProviderChain()从示例配置文件中获取凭据并允许访问s3 bucket

rdrgkggo  于 2023-11-17  发布在  Spring
关注(0)|答案(1)|浏览(168)

我正在处理一个要求,我想使用springboot应用程序连接到s3 bucket。当我通过本地环境连接时,我使用seetingloadCredentials(true),它使用Amazon STS,使用角色获取临时凭据并允许访问s3 bucket。
当我部署到qa/prd环境时,我设置了loadCredentials(false),它使用DefaultAWSCredentialsProviderChain()类从aws示例配置文件(角色分配给ec2示例)中获取凭证,并允许访问s3 bucket。我的代码是

@Configuration
   public class AmazonS3Config
   { 
static String clientRegion = "ap-south-1";
static String roleARN = "arn:aws:iam::*************:role/awss3acess";
static String roleSessionName = "bucket_storage_audit";
String bucketName = "testbucket";

//Depending on environment is set to true(for local environment) or false(for qa and prd environment)
private static AWSCredentialsProvider loadCredentials(boolean isLocal) {
    final AWSCredentialsProvider credentialsProvider;
    if (isLocal) {
        AWSSecurityTokenService stsClient = AWSSecurityTokenServiceAsyncClientBuilder.standard()
                .withCredentials(new ProfileCredentialsProvider())
                .withRegion(clientRegion)
                .build();

        AssumeRoleRequest assumeRoleRequest = new AssumeRoleRequest().withDurationSeconds(3600)
                .withRoleArn(roleARN)
                .withRoleSessionName(roleSessionName);

        AssumeRoleResult assumeRoleResult = stsClient.assumeRole(assumeRoleRequest);
        Credentials creds = assumeRoleResult.getCredentials();

        credentialsProvider = new AWSStaticCredentialsProvider(
                new BasicSessionCredentials(creds.getAccessKeyId(),
                        creds.getSecretAccessKey(),
                        creds.getSessionToken())
        );
    } else {
        
        System.out.println("inside default");
        credentialsProvider = new DefaultAWSCredentialsProviderChain();
    }

    return credentialsProvider;
}

字符串
// Amazon s3 client Bean返回s3 client的示例。@Bean public AmazonS 3 s3 client(){

AmazonS3 s3Client = AmazonS3ClientBuilder.standard()
              .withRegion(Regions.fromName(clientRegion))
                          .withCredentials(loadCredentials(false))
                          .build();
  
  return s3Client;
}
}


我的问题是,由于示例配置文件的凭据每12小时轮换一次,因此我的应用程序将在12小时后失败。我将如何避免在代码中发生这种情况?

atmip9wb

atmip9wb1#

您可以直接使用ProfileCredentialsProvider而不是DefaultAWSCredentialsProviderChain,因为在您的情况下不需要链接credsprovider。
关于你的问题,AWSCredentialsProviderrefresh()方法,它会重新读取配置文件。当使用S3客户端时出现身份验证异常时,你可以再次重试并首先调用refresh()

相关问题