Search code examples
springspring-bootspring-data-jpaaws-java-sdk

Spring boot application properties load process change programatically to improve security


I have spring boot micro-service with database credentials define in the application properties.

spring.datasource.url=<<url>>
spring.datasource.username=<<username>>
spring.datasource.password=<<password>>

We do not use spring data source to create the connection manually. Only Spring create the database connection with JPA.(org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration)

We only provide the application properties, but spring create the connections automatically to use with the database connection pool.

Our requirement to enhance the security without using db properties in clear text. Two possible methods.

  1. Encrypt the database credentials
  2. Use the AWS secret manager. (then get the credential with the application load)

For the option1, jasypt can be used, since we are just providing the properties only and do not want to create the data source manually, how to do to understand by the spring framework is the problem. If better I can get some working sample or methods.

Regarding the option-2,

  • first we need to define secretName.
  • use the secertName and get the database credentials from AWS secret manager.
  • update the application.properties programatically to understand by spring framework. (I need to know this step)

I need to use either option1 and option2. Mentioned the issues with each option.


Solution

  • I have found the solution for my problem.

    We need to define org.springframework.context.ApplicationListenerin spring.factories file. It should define the required application context listener like below.

    org.springframework.context.ApplicationListener=com.sample.PropsLoader
    

    PropsLoader class is like this.

    public class PropsLoader implements ApplicationListener<ApplicationEnvironmentPreparedEvent> {
    
    
    @Override
    public void onApplicationEvent(ApplicationEnvironmentPreparedEvent event) {
    
        ConfigurableEnvironment environment = event.getEnvironment();
    
        String appEnv          = environment.getProperty("application.env");
        //set new properties based on the application environment.  
        // calling other methods and depends on the enviornment and get the required value set  
        Properties props       = new Properties();
        props.put("new_property", "value");
    
        environment.getPropertySources().addFirst(new PropertiesPropertySource("props", props));
    
    }
    
    }
    

    spring.factories file should define under the resources package and META-INF folder.

    enter image description here

    This will set the application context with new properties before loading any other beans.