AWS Security Token Service (STS) is an Amazon web service which enables you to request temporary, limited-privilege credentials for AWS Identity and Access Management (IAM) users or for users that you authenticate (federated users). By default, the AWS Security Token Service (AWS STS) is available as a global service, and all AWS STS requests go to a single endpoint at https://sts.amazonaws.com. You can optionally send your AWS STS requests to endpoints in any of the AWS regions shown in the table that follows.
In this post, you would learn how to use AWS security token service to create temporary security credentials with Spring Boot and Java app. I would recommend using AWS STS for creating temporary credentials for development purpose with Amazon/AWS services.
Execute command such as the following to configure AWS credentials; This would be used to create temporary security credentials.
aws configure
Make sure to appropriately set the AWS region parameter. Ensure that AWS credentials have been set properly by access the file such as ~/.aws/credentials
First and foremost, create beans such as SessionCrendentials which is used for creating temporary credentials. The following are some of the key steps in creating the session credential bean:
@Configuration @PropertySource("classpath:application.properties") public class AppConfig { private static final Integer TEMPORARY_CREDENTIALS_DURATION_DEFAULT = 7200; @Value("${aws.region}") String awsRegion; @Value("${aws.s3.data.bucket}") String awsS3DataBucket; @Value("${aws.temporary.credentials.validity.duration}") String credentialsValidityDuration; @Bean(name = "awsRegion") public Region awsRegion() { return Region.getRegion(Regions.fromName(awsRegion)); } @Bean(name = "sessionCredentials") public BasicSessionCredentials sessionCredentials() { // // Create an instance of AWSSecurityTokenServiceClient // AWSSecurityTokenServiceClient sts_client = (AWSSecurityTokenServiceClient) AWSSecurityTokenServiceClientBuilder.defaultClient(); // // Get session token request object; Set credentials validity duration // GetSessionTokenRequest session_token_request = new GetSessionTokenRequest(); if(this.credentialsValidityDuration == null || this.credentialsValidityDuration.trim().equals("")) { session_token_request.setDurationSeconds(TEMPORARY_CREDENTIALS_DURATION_DEFAULT); } else { session_token_request.setDurationSeconds(Integer.parseInt(this.credentialsValidityDuration)); } // // Create an instance of GetSessionTokenResult using session token object // GetSessionTokenResult session_token_result = sts_client.getSessionToken(session_token_request); Credentials session_creds = session_token_result.getCredentials(); // // Create an instance of BasicSessionCredentials // BasicSessionCredentials sessionCredentials = new BasicSessionCredentials( session_creds.getAccessKeyId(), session_creds.getSecretAccessKey(), session_creds.getSessionToken()); return sessionCredentials; } @Bean(name = "awsS3DataBucket") public String awsS3DataBucket() { return awsS3DataBucket; } }
The code given below uses BasicSessionCredentials Bean to instantiate the Amazon S3 service.
@Component("awsCloudStorage") public class AWSCloudStorage implements CloudStorage { @Autowired String awsS3DataBucket; private AmazonS3 amazonS3; public AWSCloudStorage(@Autowired Region awsRegion, @Autowired BasicSessionCredentials sessionCredentials) { this.amazonS3 = AmazonS3ClientBuilder.standard() .withCredentials(new AWSStaticCredentialsProvider(sessionCredentials)).build(); } public void uploadFile(String keyName, String filePath) { try { this.amazonS3.putObject(this.awsS3DataBucket, keyName, filePath); } catch (AmazonServiceException e) { System.err.println(e.getErrorMessage()); } } }
Pay attention to the following code which is used to create Amazon S3 instance:
this.amazonS3 = AmazonS3ClientBuilder.standard() .withCredentials(new AWSStaticCredentialsProvider(sessionCredentials)).build();
Amazon S3 instance could as well be created with region using code such as following:
this.amazonS3 = AmazonS3ClientBuilder.standard() .withRegion(awsRegion.getName()) .withCredentials(new AWSStaticCredentialsProvider(sessionCredentials)).build();
You could provide configuration details such as temporary credentials validity duration, aws region etc in the src/main/resources/application.properties file. The following is the sample code:
aws.access.key.id = aws.access.key.secret = aws.region = us-east-1 aws.s3.data.bucket = remainders-25022018 aws.temporary.credentials.validity.duration =
The following represents the Spring Boot app code which tests the AWSCloudStorage which is instantiated using temporary credentials as shown in the code given above.
@SpringBootApplication public class RecruiterbotApplication implements CommandLineRunner { @Autowired CloudStorage awsCloudStorage; public static void main(String[] args) { SpringApplication app = new SpringApplication(RecruiterbotApplication.class); app.run(args); } @Override public void run(String... arg0) throws IOException, JavaLayerException { this.awsCloudStorage.uploadFile("message123.txt", "/home/support/Documents/corpus.lm"); } }
In this post, you learned about getting started with using temporary security credentials for accessing Amazon/AWS services from Spring Boot, Java app.
Did you find this article useful? Do you have any questions or suggestions about this article in relation to getting started with temporary security credentials using AWS STS? Leave a comment and ask your questions and I shall do my best to address your queries.
In recent years, artificial intelligence (AI) has evolved to include more sophisticated and capable agents,…
Adaptive learning helps in tailoring learning experiences to fit the unique needs of each student.…
With the increasing demand for more powerful machine learning (ML) systems that can handle diverse…
Anxiety is a common mental health condition that affects millions of people around the world.…
In machine learning, confounder features or variables can significantly affect the accuracy and validity of…
Last updated: 26 Sept, 2024 Credit card fraud detection is a major concern for credit…