Vault in Spring Boot

Spring Boot integrates very well with HashiCorp Vault to securely manage secrets (like DB credentials, API keys, tokens) instead of hardcoding them in application.properties.

Here’s a step-by-step guide with example:


🔹 1. Setup Vault

  1. Install Vault locally (or use Docker): docker run --cap-add=IPC_LOCK -d --name=dev-vault -p 8200:8200 vault:latest
  2. Start Vault in dev mode: vault server -dev
  3. Login to Vault: export VAULT_ADDR='http://127.0.0.1:8200' vault login root
  4. Store a secret: vault kv put secret/springboot-demo username=myuser password=mypassword

🔹 2. Add Dependencies in Spring Boot

pom.xml

<dependency>
  <groupId>org.springframework.cloud</groupId>
  <artifactId>spring-cloud-starter-vault-config</artifactId>
</dependency>
<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-web</artifactId>
</dependency>

Also add Spring Cloud BOM to manage Vault versions:

<dependencyManagement>
  <dependencies>
    <dependency>
      <groupId>org.springframework.cloud</groupId>
      <artifactId>spring-cloud-dependencies</artifactId>
      <version>2023.0.0</version>
      <type>pom</type>
      <scope>import</scope>
    </dependency>
  </dependencies>
</dependencyManagement>

🔹 3. Configure Vault in Spring Boot

bootstrap.properties (or bootstrap.yml):

spring.application.name=springboot-demo
spring.cloud.vault.uri=http://127.0.0.1:8200
spring.cloud.vault.authentication=TOKEN
spring.cloud.vault.token=root
spring.cloud.vault.kv.enabled=true

Here:

  • spring.application.name → app name maps to Vault path (secret/springboot-demo).
  • TOKEN → authenticate using Vault token (other methods: AppRole, AWS, Kubernetes, etc.).

🔹 4. Use Secrets in Code

If you stored username and password inside secret/springboot-demo, you can inject them:

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

@RestController
public class VaultDemoController {

    @Value("${username}")
    private String username;

    @Value("${password}")
    private String password;

    @GetMapping("/secrets")
    public String getSecrets() {
        return "Username: " + username + ", Password: " + password;
    }
}

🔹 5. Run the App

mvn spring-boot:run

Visit:

http://localhost:8080/secrets

➡ Should print the secrets from Vault.

Leave a Reply