使用Java SDK2获取临时AWS凭证

时间:2019-05-24 10:15:51

标签: aws-sdk

AWS documentation在STS /承担角色认证方面似乎仍指AWS Java SDK1。

如果我有

  • AWS Java SDK2(v.2.5.49)
  • 角色学习
  • 外部ID

..是否可以使用这些方法进行创建:

  • accessKey
  • secretKey
  • sessionToken

1 个答案:

答案 0 :(得分:0)

一个人应该使用StsAssumeRoleCredentialsProvider为您刷新临时令牌。

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

请注意,在调用.resolveCredentials()时,AWS开发工具包2会返回不提供会话令牌的AwsCredentials。可以将返回值强制转换为提供所有这三个值的AwsSessionCredentials

val prov: AwsCredentialsProvider = ???
val creds: AwsSessionCredentials = prov.resolveCredentials().asInstanceOf[AwsSessionCredentials]