Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting temporary AWS credentials using Java SDK2

Tags:

aws-sdk

The AWS documentation seems still to refer to AWS Java SDK1 with regard to STS / assume role authentication.

If I have:

  • AWS Java SDK2 (v.2.5.49)
  • role-arn
  • external-id

..is there a way to create with those:

  • accessKey
  • secretKey
  • sessionToken
like image 832
akauppi Avatar asked Sep 16 '25 16:09

akauppi


1 Answers

One should use StsAssumeRoleCredentialsProvider that does the refreshing of temporary tokens for you.

def apply(roleArn: String, externalId: String, expires: FiniteDuration, sessionName: String): StsAssumeRoleCredentialsProvider = {
    val durationSecs: Int = expires.toSeconds.toInt

    val stsClient: StsClient = StsClient.builder.build()

    val req: AssumeRoleRequest = AssumeRoleRequest.builder
      .roleArn(roleArn)
      .externalId(externalId)
      .durationSeconds(durationSecs)
      .roleSessionName(sessionName)
      .build()

    StsAssumeRoleCredentialsProvider.builder
      .stsClient(stsClient)
      .refreshRequest(req)
      .build()
  }

Note that when calling .resolveCredentials() the AWS SDK 2 returns an AwsCredentials that does not provide the session token. The returned value can just be casted to AwsSessionCredentials which provides all the three.

val prov: AwsCredentialsProvider = ???
val creds: AwsSessionCredentials = prov.resolveCredentials().asInstanceOf[AwsSessionCredentials]
like image 130
akauppi Avatar answered Sep 19 '25 07:09

akauppi