How to integrate AWS Secrets Manager with Spring Boot

Using AWS Secrets Manager with Spring Boot allows you to securely store and retrieve secrets such as database credentials, API keys, and other sensitive configuration values. Here's how to integrate AWS Secrets Manager with Spring Boot  using the latest best practices:


1. Create a Secret in AWS Secrets Manager

1. Log in to AWS Console:

  • Go to the AWS Secrets Manager service.

2. Create a New Secret:

  • Choose the type of secret:

          1. Key/Value pairs: e.g., database credentials.

          2. Plaintext: for custom secrets.

  • Example (Key/Value pairs):

{
  "username": "db_user",
  "password": "db_password"
}


3. Name the Secret:

  • Provide a unique name (e.g., myAppSecret).

4. Store the Secret:

  • Select a region where your application will access it.


5. Grant IAM Permissions:

  • Attach a policy to your user, role, or service granting secretsmanager:GetSecretValue permission.


2. Add Dependencies to Your Spring Boot Project

Update pom.xml (Maven):

<dependency>
    <groupId>software.amazon.awssdk</groupId>
    <artifactId>secretsmanager</artifactId>
    <version>2.20.84</version> <!-- Check the latest version -->
</dependency>


Update build.gradle (Gradle):

implementation 'software.amazon.awssdk:secretsmanager:2.20.84' // Use the latest version


3. Configure AWS Secrets Manager Client

Configure your AWS credentials using one of the following:

import software.amazon.awssdk.auth.credentials.DefaultCredentialsProvider;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.secretsmanager.SecretsManagerClient;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class AwsSecretsManagerConfig {

    @Bean
    public SecretsManagerClient secretsManagerClient() {
        return SecretsManagerClient.builder()
                .region(Region.US_EAST_1) // Replace with your region
                .credentialsProvider(DefaultCredentialsProvider.create())
                .build();
    }
}


4. Create a Service to Fetch Secrets

Create a service to interact with AWS Secrets Manager.

import org.springframework.stereotype.Service;
import software.amazon.awssdk.services.secretsmanager.SecretsManagerClient;
import software.amazon.awssdk.services.secretsmanager.model.GetSecretValueRequest;
import software.amazon.awssdk.services.secretsmanager.model.GetSecretValueResponse;

@Service
public class AwsSecretsManagerService {

    private final SecretsManagerClient secretsManagerClient;

    public AwsSecretsManagerService(SecretsManagerClient secretsManagerClient) {
        this.secretsManagerClient = secretsManagerClient;
    }

    public String getSecret(String secretName) {
        GetSecretValueRequest request = GetSecretValueRequest.builder()
                .secretId(secretName)
                .build();

        GetSecretValueResponse response = secretsManagerClient.getSecretValue(request);
        return response.secretString(); // Returns the secret as a string
    }
}


5. Use the Secret in Your Application

Use the service to retrieve secrets dynamically.

Example: REST Controller

import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class SecretController {

    private final AwsSecretsManagerService secretsManagerService;

    @Value("${aws.secret.name}") // Define this in application.properties or YAML
    private String secretName;

    public SecretController(AwsSecretsManagerService secretsManagerService) {
        this.secretsManagerService = secretsManagerService;
    }

    @GetMapping("/secret")
    public String getSecret() {
        return secretsManagerService.getSecret(secretName);
    }
}


6. Add Configuration Properties

Define the secret name and AWS region in your application configuration file.

application.properties:

aws.secret.name=myAppSecret
aws.region=us-east-1
spring.application.name=my-spring-boot-app

application.yml:

aws:
  secret:
    name: myAppSecret
  region: us-east-1
spring:
  application:
    name: my-spring-boot-app


7. Grant IAM Permissions

Ensure the application has the proper IAM permissions to access the secret.

Example IAM Policy:

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Action": "secretsmanager:GetSecretValue",
      "Resource": "arn:aws:secretsmanager:REGION:ACCOUNT_ID:secret:myAppSecret"
    }
  ]
} 

  • Attach this policy to the IAM role or user accessing the secret.


8. Test the Integration

1. Start your Spring Boot application.

2. Test the /secret endpoint:

  • The secret (e.g., {"username":"db_user","password":"db_password"}) should be retrieved and displayed.


9. Deploy Application Securely

When deploying to AWS services (e.g., ECS, EC2, or Lambda), ensure:

  • Proper IAM roles are assigned.
  • Secrets are fetched dynamically and not hardcoded.

Popular posts from this blog

Learn Java 8 streams with an example - print odd/even numbers from Array and List

Java Stream API - How to convert List of objects to another List of objects using Java streams?

Registration and Login with Spring Boot + Spring Security + Thymeleaf

Java, Spring Boot Mini Project - Library Management System - Download

ReactJS, Spring Boot JWT Authentication Example

Top 5 Java ORM tools - 2024

Java - Blowfish Encryption and decryption Example

Spring boot video streaming example-HTML5

Google Cloud Storage + Spring Boot - File Upload, Download, and Delete