I need advice on how I can update AWS credentials after they expire.
I'm creating a bean of AmazonSimpleEmailService this way:
@Bean
public AmazonSimpleEmailService getSesClient() {
return AmazonSimpleEmailServiceClientBuilder.standard()
.withCredentials(new AWSStaticCredentialsProvider(new STSAssumeRoleSessionCredentialsProvider.Builder("ses-role-us-west-2", "mail-sender")
.build()
.getCredentials())
)
.withRegion(Regions.US_WEST_2).build();
}
But when I'm trying to use it I'm getting an error:
The security token included in the request is expired (Service: AmazonSimpleEmailService; Status Code: 403; Error Code: ExpiredToken
If I create an instance of the SES client right before each mail sending - it works correctly, but it looks like a bad practice to create a new instance before each use.
I understand that the issue with the credentials that I'm getting via STSAssumeRoleSessionCredentialsProvider - they just have an expiration time.
I am wondering if there should be a way to automatically update the credentials when they are going to expire, so I'd really appreciate any advice on how to do it.
STSAssumeRoleSessionCredentialsProvider
will auto-refresh the credentials, but you are blocking that functionality by getting a single set of credentials and passing them into a AWSStaticCredentialsProvider
instance.
This should allow you to use the auto-refresh of the STS Provider:
@Bean
public AmazonSimpleEmailService getSesClient() {
return AmazonSimpleEmailServiceClientBuilder.standard()
.withCredentials(new STSAssumeRoleSessionCredentialsProvider.Builder("ses-role-us-west-2", "mail-sender")
.build()
)
.withRegion(Regions.US_WEST_2).build();
}