Home > Back-end >  Using Basic Credentials to make IamClient requests
Using Basic Credentials to make IamClient requests

Time:01-04

I am using BasicCredentials to AmazonS3 requests using AWS Java SDK v2. I am trying to use the same approach to make IAmClient requests but not finding a way to do that. here is the code I am using for AmazonS3 requests:

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


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

withCredentials method is not available for IAmClient. IAmClient has a method credentialsProvider but it doesn't accept BasicAWSCredentials. Here is the code I tried for IAmClient:

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

When I run it, it says :

/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

I am not finding any relevant documentation as well. How am I supposed to use BasicAWSCredentials to make IAmClient requests?

CodePudding user response:

For Java SDK v2 you can use this code snippet:

    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();

To take into consideration:

  • Set the Region as Region.AWS_GLOBAL. Otherwise, you will get an UnknownHostException
  • Make sure you are using Java SDK v2 as it is a major change from v1 and it does not work in that previous version
  • Related