{{announcement.body}}
{{announcement.title}}

Spring Cloud + Hashicorp Vault Hello World Example

DZone 's Guide to

Spring Cloud + Hashicorp Vault Hello World Example

In this Spring Cloud Tutorial we will be making use of Hashicorp Vault to secure credentials for Microservices.

· Cloud Zone ·
Free Resource

Microservices architecture have multiple services which interact with each other and external resources like databases. They also need access to usernames and passwords to access these resources. Usually these credentials are stored in config properties. So each microservice will have its own copy of credentials. If any credentials change we will need to update the configurations in all microservices. We have previously discussed one solution to this problem is using Spring Cloud Config Native Server or Spring Cloud Config Git Server where common global properties which are repeated in all the microservices are usually stored. But still storing the secrets in configuration file is a security concern. Above approach as 2 drawbacks-

  • No single point of Truth
  • Security risk of exposing the credentials

In this tutorial will be using Spring Cloud Config and Hashicorp Vault to manage secrets and protect sensitive data.

Hashicorp Vault is a platform to secure, store, and tightly control access to tokens, passwords, certificates, encryption keys for protecting sensitive data and other secrets in a dynamic infrastructure.
Using vault we will be retrieving the credentials from the vault key/value store.

We will be implementing a simple Spring Boot Microservice which returns employee details from MySql Database. We will be creating the Spring Boot + MySQL Application using Spring Boot JDBC. We have already seen Spring Boot MYSQL JDBC basics in a previous tutorial. In We will be initially storing the MySql credentials in the configuration file.

Later we will be modifying this application to fetch the MySQL credentials from HashiCorp Vault.

Spring Boot + MySQL Application

The project will be as follows —

Add the spring-jdbc-starter dependency.

XML
 




x
37


 
1
<?xml version="1.0" encoding="UTF-8"?>
2
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
3
 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4
 <modelVersion>4.0.0</modelVersion><groupId>com.javainuse</groupId>
5
 <artifactId>boot-jdbc</artifactId>
6
 <version>0.0.1-SNAPSHOT</version>
7
 <packaging>jar</packaging><name>boot-jdbc</name>
8
 <description>Demo project for Spring Boot</description><parent>
9
  <groupId>org.springframework.boot</groupId>
10
  <artifactId>spring-boot-starter-parent</artifactId>
11
  <version>2.3.0.RELEASE</version>
12
  <relativePath /> <!-- lookup parent from repository -->
13
 </parent><properties>
14
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
15
<project.reporting.outputEncoding>UTF-8 </project.reporting.outputEncoding>
16
  <java.version>1.8</java.version>
17
 </properties><dependencies>
18
  <dependency>
19
   <groupId>org.springframework.boot</groupId>
20
   <artifactId>spring-boot-starter-web</artifactId>
21
  </dependency>
22
  <dependency>
23
   <groupId>org.springframework.boot</groupId>
24
   <artifactId>spring-boot-starter-jdbc</artifactId>
25
  </dependency><dependency>
26
   <groupId>mysql</groupId>
27
   <artifactId>mysql-connector-java</artifactId>
28
   <scope>runtime</scope>
29
  </dependency>
30
 </dependencies><build>
31
  <plugins>
32
   <plugin>
33
    <groupId>org.springframework.boot</groupId>
34
    <artifactId>spring-boot-maven-plugin</artifactId>
35
   </plugin>
36
  </plugins>
37
 </build></project>


In the application.properties file specify the datasource properties

XML
 




xxxxxxxxxx
1


1
spring.datasource.url=jdbc:mysql://localhost/bootdb?createDatabaseIfNotExist=true&autoReconnect=true&useSSL=false
2
spring.datasource.username=root
3
spring.datasource.password=root
4
spring.datasource.platform=mysql
5
spring.datasource.initialization-mode=always



Create the schema-mysql.sql file and specify the initialization scripts —

XML
 




xxxxxxxxxx
1


 
1
DROP TABLE IF EXISTS employee;CREATE TABLE employee (
2
  empId VARCHAR(10) NOT NULL,
3
  empName VARCHAR(100) NOT NULL
4
);INSERT INTO employee(empId,empName)values("emp001","emp1");
5
INSERT INTO employee(empId,empName)values("emp002","emp2");
6
INSERT INTO employee(empId,empName)values("emp003","emp3");



Create the Employee Domain class

Java
 




x


1
package com.javainuse.model;
2
 
          
3
public class Employee {
4
 
          
5
    private String empId;
6
    private String empName;
7
 
          
8
    public String getEmpId() {
9
        return empId;
10
    }
11
 
          
12
    public void setEmpId(String empId) {
13
        this.empId = empId;
14
    }
15
 
          
16
    public String getEmpName() {
17
        return empName;
18
    }
19
 
          
20
    public void setEmpName(String empName) {
21
        this.empName = empName;
22
    }
23
 
          
24
    @Override
25
    public String toString() {
26
        return "Employee [empId=" + empId + ", empName=" + empName + "]";
27
    }
28
 
          
29
}



Create the DAO interface.

Java
 




xxxxxxxxxx
1


 
1
package com.javainuse.dao;
2
 
          
3
import java.util.List;
4
 
          
5
import com.javainuse.model.Employee;
6
 
          
7
public interface EmployeeDao {
8
    List<Employee> getAllEmployees();
9
}



The DAO implementation class.

Java
 




xxxxxxxxxx
1
43


1
package com.javainuse.dao.impl;
2
 
          
3
import java.util.ArrayList;
4
import java.util.List;
5
import java.util.Map;
6
 
          
7
import javax.annotation.PostConstruct;
8
import javax.sql.DataSource;
9
 
          
10
import org.springframework.beans.factory.annotation.Autowired;
11
import org.springframework.jdbc.core.support.JdbcDaoSupport;
12
import org.springframework.stereotype.Repository;
13
 
          
14
import com.javainuse.dao.EmployeeDao;
15
import com.javainuse.model.Employee;
16
 
          
17
@Repository
18
public class EmployeeDaoImpl extends JdbcDaoSupport implements EmployeeDao {
19
 
          
20
    @Autowired
21
    DataSource dataSource;
22
 
          
23
    @PostConstruct
24
    private void initialize() {
25
        setDataSource(dataSource);
26
    }
27
 
          
28
    @Override
29
    public List<Employee> getAllEmployees() {
30
        String sql = "SELECT * FROM employee";
31
        List<Map<String, Object>> rows = getJdbcTemplate().queryForList(sql);
32
 
          
33
        List<Employee> result = new ArrayList<Employee>();
34
        for (Map<String, Object> row : rows) {
35
            Employee emp = new Employee();
36
            emp.setEmpId((String) row.get("empId"));
37
            emp.setEmpName((String) row.get("empName"));
38
            result.add(emp);
39
        }
40
 
          
41
        return result;
42
    }
43
}



Create Service interface to specify employee operations to be performed.

Java
 




xxxxxxxxxx
1


 
1
package com.javainuse.service;
2
 
          
3
import java.util.List;
4
 
          
5
import com.javainuse.model.Employee;
6
 
          
7
public interface EmployeeService {
8
    List<Employee> getAllEmployees();
9
}



The Service class implementation.

Java
 




xxxxxxxxxx
1
23


1
package com.javainuse.service.impl;
2
 
          
3
import java.util.List;
4
 
          
5
import org.springframework.beans.factory.annotation.Autowired;
6
import org.springframework.stereotype.Service;
7
 
          
8
import com.javainuse.dao.EmployeeDao;
9
import com.javainuse.model.Employee;
10
import com.javainuse.service.EmployeeService;
11
 
          
12
@Service
13
public class EmployeeServiceImpl implements EmployeeService {
14
 
          
15
    @Autowired
16
    EmployeeDao employeeDao;
17
 
          
18
    public List<Employee> getAllEmployees() {
19
        List<Employee> employees = employeeDao.getAllEmployees();
20
        return employees;
21
    }
22
 
          
23
}



Create the Controller class to expose a GET API which fetches the employee records.

Java
 




xxxxxxxxxx
1
26


 
1
package com.javainuse.controller;
2
 
          
3
import java.util.List;
4
 
          
5
import org.springframework.beans.factory.annotation.Autowired;
6
import org.springframework.web.bind.annotation.RequestMapping;
7
import org.springframework.web.bind.annotation.RequestMethod;
8
import org.springframework.web.bind.annotation.RestController;
9
 
          
10
import com.javainuse.model.Employee;
11
import com.javainuse.service.EmployeeService;
12
 
          
13
@RestController
14
public class EmployeeController {
15
 
          
16
    @Autowired
17
    EmployeeService empService;
18
 
          
19
    @RequestMapping(value = "/employees", method = RequestMethod.GET)
20
    public List<Employee> firstPage() {
21
 
          
22
        return empService.getAllEmployees();
23
 
          
24
    }
25
 
          
26
}



Finally create the class with @SpringBootApplication annotation.

Java
 




xxxxxxxxxx
1
14


 
1
package com.javainuse;
2
 
          
3
import org.springframework.beans.factory.annotation.Autowired;
4
import org.springframework.boot.SpringApplication;
5
import org.springframework.boot.autoconfigure.SpringBootApplication;
6
 
          
7
@SpringBootApplication
8
public class SpringBootJdbcApplication {
9
 
          
10
    public static void main(String[] args) {
11
        SpringApplication.run(SpringBootJdbcApplication.class, args);
12
    }
13
}
14
 
          



Start the application. And got to localhost:8080/employees.

Download and Setup Hashicorp Vault

Go to Hashicorp download Page and download Hashicorp Vault.

This is a zip file. Unzip it contains vault.exe. Create a file name vaultconfig.hcl for configuring vault on startup.

Java
 




xxxxxxxxxx
1


 
1
storage "file" {
2
    path= "./vault-data"
3
}listener "tcp" {
4
  address = "127.0.0.1:8200"
5
  tls_disable =1        
6
}disable_mlock=true



Open a command prompt and run the following vault commands-

vault server -config ./vaultconfig.hcl

Vault is now started. Open another command prompt and run the following commands-

set VAULT_ADDR=http://localhost:82

vault operator init

set VAULT_TOKEN=s.wO85qvAKuzL4QQifLE9N5aiq

vault status

We can see here that the Vault is sealed. We need to unseal it.

Java
 




xxxxxxxxxx
1


 
1
vault operator unseal Y2fJhNi5AXU3HdShQ4p0bZ/KfXVWU3ZYRwaecnlkEYYP
2
vault operator unseal XS/NJF3X/OcrVzoM9a5oSG2D7Mls2+WCE104RgCAJLrH
3
vault operator unseal W+W/R7Dwgaj+qwPsrKo3RBDxSzrfoW917AwgoAzvFcOT



Next enable a key value store with named secrets

vault secrets enable -path=secret/ kv

Store the MySql username and password in the Hashicorp Vault

vault kv put secret/javainuseapp dbusername=root

vault kv put secret/javainuseapp dbpassword=root

Configure Spring Cloud Config in Spring Boot Application

In the pom.xml add the Spring Cloud dependencies —

Java
 




xxxxxxxxxx
1
61


 
1
<name>boot-jdbc</name>
2
    <description>Demo project for Spring Boot</description>
3
 
          
4
    <parent>
5
        <groupId>org.springframework.boot</groupId>
6
        <artifactId>spring-boot-starter-parent</artifactId>
7
        <version>2.3.0.RELEASE</version>
8
        <relativePath /> <!-- lookup parent from repository -->
9
    </parent>
10
 
          
11
    <properties>
12
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
13
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
14
        <java.version>1.8</java.version>
15
        <spring-cloud.version>Hoxton.SR1</spring-cloud.version>
16
    </properties>
17
 
          
18
    <dependencies>
19
        <dependency>
20
            <groupId>org.springframework.boot</groupId>
21
            <artifactId>spring-boot-starter-web</artifactId>
22
        </dependency>
23
        <dependency>
24
            <groupId>org.springframework.boot</groupId>
25
            <artifactId>spring-boot-starter-jdbc</artifactId>
26
        </dependency>
27
        <dependency>
28
        <groupId>org.springframework.cloud</groupId>
29
        <artifactId>spring-cloud-starter-vault-config</artifactId>
30
        </dependency>
31
 
          
32
        <dependency>
33
            <groupId>mysql</groupId>
34
            <artifactId>mysql-connector-java</artifactId>
35
            <scope>runtime</scope>
36
        </dependency>
37
    </dependencies>
38
    
39
    <dependencyManagement>
40
        <dependencies>
41
            <dependency>
42
                <groupId>org.springframework.cloud</groupId>
43
                <artifactId>spring-cloud-dependencies</artifactId>
44
                <version>${spring-cloud.version}</version>
45
                <type>pom</type>
46
                <scope>import</scope>
47
            </dependency>
48
        </dependencies>
49
    </dependencyManagement>
50
 
          
51
    <build>
52
        <plugins>
53
            <plugin>
54
                <groupId>org.springframework.boot</groupId>
55
                <artifactId>spring-boot-maven-plugin</artifactId>
56
            </plugin>
57
        </plugins>
58
    </build>
59
 
          
60
 
          
61
</project>



Create a file name bootstrap.yml and add the following configuration.

Java
 




xxxxxxxxxx
1


 
1
spring:
2
  application:
3
    name: javainuseapp
4
  cloud:
5
    vault:
6
      host: localhost
7
      port: 8200
8
      scheme: http
9
      token: s.wO85qvAKuzL4QQifLE9N5aiq



Finally in the application.properties change the MySql username and password properties to get values from Hashicorp Vault.

Java
 




xxxxxxxxxx
1


 
1
spring.datasource.url=jdbc:mysql://localhost/bootdb?createDatabaseIfNotExist=true&autoReconnect=true&useSSL=false
2
spring.datasource.username=${dbusername}
3
spring.datasource.password=${dbpassword}
4
spring.datasource.platform=mysql
5
spring.datasource.initialization-mode=always



If we now start the Spring Boot Application, it will automatically fetch the MySql username and password by making an API call to Vault.

Topics:
cloud, hashicorp, spring boot, spring cloud, spring cloud config, spring secruity, tutorial

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}