adi.sah
adi.sah

Reputation: 81

SQS ExpiredToken: The security token included in the request is expired status code:

I am trying to connect to AWS sqs after assume rule, and im getting expired security token errors after an hour, how can i auto refresh the connection?

@Bean
    public QueueMessagingTemplate queueMessagingTemplate(){
        return new QueueMessagingTemplate(amazonSQSAsync());
    }

    private AmazonSQSAsync amazonSQSAsync(){
        try {
            logger.info("Start amazonSQSAsync");

            AWSSecurityTokenService stsClient = AWSSecurityTokenServiceClientBuilder.standard()
                    .withCredentials(new DefaultAWSCredentialsProviderChain())
                    .withRegion(AWS_REGION)
                    .build();
            logger.info("stsClient created successfully");
            AssumeRoleRequest roleRequest = new AssumeRoleRequest()
                    .withRoleArn(ROLE_ARN)
                    .withRoleSessionName(ROLE_SESSION_NAME)
                    .withDurationSeconds(3600);
            AssumeRoleResult assumeRoleResult = stsClient.assumeRole(roleRequest);
            logger.info("assumeRoleResult created successfully");
            BasicSessionCredentials basicSessionCredentials = new BasicSessionCredentials(
                    assumeRoleResult.getCredentials().getAccessKeyId(),
                    assumeRoleResult.getCredentials().getSecretAccessKey(),
                    assumeRoleResult.getCredentials().getSessionToken());
            logger.info("basicSessionCredentials created successfully");
            AmazonSQSAsync amazonSQSAsync = AmazonSQSAsyncClientBuilder.standard()
                    .withCredentials(new AWSStaticCredentialsProvider(basicSessionCredentials))
                .withRegion(AWS_REGION).build();
//                    .withEndpointConfiguration(new AwsClientBuilder.EndpointConfiguration(SQS_URL,"us-east-2"))
            logger.info("amazonSQSAsync created successfully");
            return amazonSQSAsync;
        } catch (Exception e){
            logger.error("Failed to create Amazon sqs client", e);
            throw e;
        }
    }

Upvotes: 2

Views: 1991

Answers (1)

guest
guest

Reputation: 901

You can get auto-renewing credentials from STSAssumeRoleSessionCredentialsProvider:

AWSSecurityTokenService stsClient 
    = AWSSecurityTokenServiceClientBuilder.defaultClient();

STSAssumeRoleSessionCredentialsProvider assumedRoleCredentialsProvider
    = new STSAssumeRoleSessionCredentialsProvider.Builder(ROLE_ARN, SESSION_ID)
      .withStsClient(stsClient)
      .build();

AmazonSQS sqsClient 
    = AmazonSQSClientBuilder.standard()
      .withCredentials(assumedRoleCredentialsProvider)
      .build();

Note that you can't shutdown stsClient while you are using the derived clients. Per AWS recommendations, create a singleton instance that lasts the lifetime of your program.

Upvotes: 6

Related Questions