使用基本凭证发出 IamClient 请求

Using Basic Credentials to make IamClient requests

我正在使用 BasicCredentials AmazonS3 使用 AWS Java SDK v2 的请求。我正在尝试使用相同的方法来发出 IAmClient 请求,但没有找到这样做的方法。这是我用于 AmazonS3 请求的代码:

        BasicAWSCredentials awsCreds = new BasicAWSCredentials("accesskey", "secretey");


    AmazonS3 s3Client = AmazonS3ClientBuilder.standard()
            .withCredentials(new AWSStaticCredentialsProvider(awsCreds))
            .withRegion(Regions.US_EAST_2)
            .build();

withCredentials 方法不适用于 IAmClientIAmClient 有一个方法 credentialsProvider 但它不接受 BasicAWSCredentials。这是我为 IAmClient 尝试的代码:

        BasicAWSCredentials awsCreds = new BasicAWSCredentials("accesskey", "secretey");
        IamClient iam = IamClient.builder().credentialsProvider(awsCreds)
            .region(region)
            .build();

当我 运行 它时,它说:

/home/jamshaid/IdeaProjects/AWSTestS3/src/main/java/test/ListUsers.java:40: error: incompatible types: com.amazonaws.auth.BasicAWSCredentials cannot be converted to software.amazon.awssdk.auth.credentials.AwsCredentialsProvider

我也没有找到任何相关文档。我应该如何使用 BasicAWSCredentials 发出 IAmClient 请求?

对于 Java SDK v2,您可以使用此代码段:

    Region region = Region.AWS_GLOBAL;
    AwsBasicCredentials awsCreds = AwsBasicCredentials.create("ACCESS_KEY", "SECRET_ACCESS_KEY");
    StaticCredentialsProvider credentialsProvider = StaticCredentialsProvider.create(awsCreds);
    
    IamClient iam = IamClient.builder()
        .credentialsProvider(credentialsProvider)
        .region(region)
        .build();
    
    ListRolesResponse listRoles = iam.listRoles();

要考虑:

  • 将区域设置为Region.AWS_GLOBAL。否则,您将得到一个 UnknownHostException
  • 确保您使用的是 Java SDK v2,因为它是对 v1 的重大更改,并且在之前的版本中不起作用