Configuration of AWS Secret Manager with Spring Boot
Deepak Patil
Posted on May 18, 2024
In this post, we will see how to configure AWS Secret Manager with Spring Boot Application. Secret manager can be very useful for managing service secrets, API keys, Database credentials and other secrets for deploying applications.
Let's set up Secret Manager with the Spring Boot application.
Step 1: Creating Project
Create a spring boot project with Java and Maven using Favourite IDE or Spring Initializr.
The project must have Spring Web and Lombok as dependencies. Get the reference code from below link
Step 2: Add dependencies for Secret Manager.
Now let's specify the required dependencies for the Secret manager configuration.
To use secret manager AWS SDK for JAVA has to be configured in the project. Add aws-sdk dependency in the project.
<dependency>
<groupId>com.amazonaws</groupId>
<artifactId>aws-java-sdk-core</artifactId>
<version>1.12.721</version>
</dependency>
- Also we will add secret manager dependency as below.
<dependency>
<groupId>software.amazon.awssdk</groupId>
<artifactId>secretsmanager</artifactId>
<version>2.25.50</version>
</dependency>
- AWS SDK requires authentication credentials for accessing AWS resources. To configure access follow the steps mentioned in the below docs page of AWS.
For this project, we will be using the SSO login option.
Once done with the configuration of SDK. Let's add AWS SSO dependencies to the project.
<dependency>
<groupId>software.amazon.awssdk</groupId>
<artifactId>sso</artifactId>
<version>2.25.50</version>
</dependency>
<dependency>
<groupId>software.amazon.awssdk</groupId>
<artifactId>ssooidc</artifactId>
<version>2.25.52</version>
</dependency>
Step 3 : Configure secret manager
- Create Secret Manager Client using builder as below. (The Region mentioned in client must be same as region where secret is created)
secretsManagerClient = SecretsManagerClient.builder().region(Region.AP_SOUTH_1).build();
Now create a method to fetch the secrets.
For fetching secrets we require GetSecretValueRequest which can be created as below. SecretName is the name of secret stored in AWS.
GetSecretValueRequest getSecretValueRequest = GetSecretValueRequest.builder()
.secretId(secretName)
.build();
- Finally call getValueRequest() method of client with GetSecretValueRequest to get the response (GetSecretValueResponse)
GetSecretValueResponse valueResponse = secretsManagerClient.getSecretValue(getSecretValueRequest);
properties.setProperty(secretName, valueResponse.secretString());
- secret string can be fetched using secretString() method of valueResponse object.
Thus we have configured the secret manager in spring boot successfully. Secrets can be fetched automatically based on application events in Spring Boot but that's the topic for another article.
Thank You!
Posted on May 18, 2024
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.