user2324686
user2324686

Reputation: 71

Using AWS SDK for Java V1 to assume role. Its not working

I am trying to assume an aws role to connect to different service. I have following implementation which is not working fine. It is giving me error

javax.net.ssl.SSLException: Connection reset

Any thoughts on how to fix this?

public static Credentials assumeRole() {

    String targetRoleArn = "xxx";
    String assumedRoleName = "xxx";

    String accessKey = "xxx";
    String secretKey = "xxx";
    
    Credentials assumedCredentials = null;      

    AwsBasicCredentials credentials = AwsBasicCredentials.create(accessKey, secretKey);

    StsClient stsClient = StsClient.builder()
            .region(Region.US_EAST_1)
            .credentialsProvider(StaticCredentialsProvider.create(credentials))
            .build();

    try {
        AssumeRoleRequest roleRequest = AssumeRoleRequest.builder()
                .roleArn(targetRoleArn)
                .roleSessionName(assumedRoleName)
                .build();

        AssumeRoleResponse roleResponse = stsClient.assumeRole(roleRequest);

        assumedCredentials = roleResponse.credentials();

    } catch (StsException e) {
        System.err.println(e.getMessage());
        System.exit(1);
    }
    
    return assumedCredentials;
    
}

Upvotes: 0

Views: 1444

Answers (1)

smac2020
smac2020

Reputation: 10734

I strongly suggest that you move from AWS SDK for Java V1 to AWS SDK for Java V2, which is considered best practice. V1 is not recommended anymore, as described in this AWS Page.

For this use case, there is an example in AWS Code Lib using AWS SDK for Java V2. This example perform these tasks:

  1. Creates a user that has no permissions.
  2. Creates a role and policy that grants Amazon S3 permissions.
  3. Creates a role.
  4. Grants the user permissions.
  5. Gets temporary credentials by assuming the role. Creates an Amazon S3 Service client object with the temporary credentials.
  6. Deletes the resources.

See:

Create an IAM user and assume a role with AWS STS using an AWS SDK

OR full example in GitHub:

https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/javav2/example_code/iam/src/main/java/com/example/iam/IAMScenario.java

This V2 code has been tested many times and works (as all code in AWS Code Library) - as shown here.

enter image description here

Upvotes: 1

Related Questions