Spring data JPA - Do not hard code password in XML file

Viewed 617

I am writing a Spring Jar (Without Spring boot) which connects to database. Almost all the tutorials which I saw connects to Database using the spring XML and the password is hard coded in the XML file. This is in no way allowed in production environment and way out of standards in terms of security.

Can someone please help me if there is a way to inject password from a method call which inturn retrieves the password from a secured vault and provides the password to datasource object in runtime.

something like below.

    <bean id="dataSource" class="org.springframework.jdbc.datasource.SingleConnectionDataSource">
    <property name="driverClassName" value="org.postgresql.Driver" />
    <property name="url" value="jdbc:postgresql://localhost:5432/postgres" />
    <property name="username" value="postgres" />
    <property name="password" value=getPasswordfromSecureVault("username") />
    <property name="suppressClose" value="true" />
    <jdbc:initialize-database  >
    <jdbc:script location="create-tables.sql"/>
    </jdbc:initialize-database>
1 Answers

Based on the spring boot tag that you have, I'll assume that you're using spring boot for your project. With spring boot, it is very easy to externalize configuration for your application. It also auto-configures your datasource with a connection pool if you use the starters they provide.

In your case, you could benefit from moving to using spring boot's Externalized Configuration. What that would allow you to do is to use an environment variable to configure your spring application. For example, to configure your password, use the environment variable SPRING_DATASOURCE_PASSWORD. You could also use the Java option -Dspring.datasource.password=[password] when starting the application, for example: java -jar -Dspring.datasource.password=password app.jar

If using docker containers, the environment variable way is generally my go to as it's very straight forward for people to understand.

If you really want to configure the password from a method call, you can do that too using java configuration. Create a bean of type DataSource and Spring should pick it up and use it.

@Configuration
class AppConfiguration {
    @Bean
    public DataSource dataSource() {
       String password = // Get your password
       return DataSourceBuilder.create().password(password).build();
    }
}
Related