amazon-web-servicesaws-sts

How to renew token in sts


I am using aws sts service to connect with amazon resources. I have the following java code for that purpose

 AssumeRoleRequest roleRequest = AssumeRoleRequest.builder()
                        .roleArn(roleArm)
                        .roleSessionName(roleSessionName)
                        .build();
             
  AssumeRoleResponse roleResponse = stsClient.assumeRole(roleRequest);
             
  sessionCredentials = roleResponse.credentials();
         
  stsCredentials = AwsSessionCredentials.create(
                     sessionCredentials.accessKeyId(),
                     sessionCredentials.secretAccessKey(),
                     sessionCredentials.sessionToken()); 
             
  provider = StaticCredentialsProvider.create(stsCredentials);

At first I was under the impression that I didnt have to detect the token expiration and renew it at given time intervals (I thought the service would renew it itself) but it seems that the token expires after a certain time interval.

How do I detect and renew the token?


Solution

  • How do I detect and renew the token?

    Your AssumeRoleResponse should give you expiration. So you have to monitor it, and when few minutes before your credentials expire, you have to create new credentials yourself. There is no automatic renew, unless you run your code on EC2 instance, ECS container or a lambda function. In that case, AWS take cares of this process.