AWSSecurityTokenServiceClient provides a getSessionToken() method with the following description:
I wanted to get a token valid for two hours. It took me quite a while to figure out how to get a session using IAM credentials instead of AWS credentials. I spent some time searching and checking out the com.amazonaws.services.identitymanagement package to see if it could provide a way to connect with IAM credentials. However it turned out to be much simpler. You need to create a BasicAWSCredentials object with your IAM access and secret key passed to the constructor. Then pass this object when instantiating AWSSecurityTokenServiceClientThe GetSessionToken action returns a set of temporary credentials for an AWS account or IAM user. The credentials consist of an Access Key ID, a Secret Access Key, and a security token. These credentials are valid for the specified duration only. The session duration for IAM users can be between 15 minutes and 36 hours, with a default of 12 hours. The session duration for AWS account owners is restricted to a maximum of one hour. Providing the AWS Multi-Factor Authentication (MFA) device serial number and the token code is optional.For more information about using GetSessionToken to create temporary credentials, go to Creating Temporary Credentials to Enable Access for IAM Users in Using IAM .
public Credentials getS3Token() {
try {
BasicAWSCredentials creds = new BasicAWSCredentials("XXXXXXX", "XXXXXXXXX");
AWSSecurityTokenServiceClient awsSecurityTokenServiceClient = new AWSSecurityTokenServiceClient(creds);
GetSessionTokenRequest getSessionTokenRequest = new GetSessionTokenRequest();
getSessionTokenRequest.setDurationSeconds(7200); // 2 hours
GetSessionTokenResult gstr = awsSecurityTokenServiceClient.getSessionToken(getSessionTokenRequest);
log.info(gstr.getCredentials().toString());
return gstr.getCredentials();
} catch (AmazonServiceException ase) {
log.error("Caught Exception: " + ase.getMessage());
log.debug("Reponse Status Code: " + ase.getStatusCode());
log.debug("Error Code: " + ase.getErrorCode());
log.debug("Request ID: " + ase.getRequestId());
} catch (Exception e) {
log.error("IOException");
e.printStackTrace();
}
return null;
}