Issue
I am using Spring JPA to access my database but the username and password for the database is provided to me in the form of two files (username.txt and password.txt). The security guideline is that we are not supposed to paste password or any form of password (encrypted) in the config files.
I am trying to figure out ways to do something like this:
spring.datasource:
url: <db url>
username: "file:/path/username.txt"
password: "file:/path/password.txt"
Does anyone have any idea on how to achieve something very similar to this?
PS. I want to keep the environment-specific credential file paths in this spring properties file. There are ways to pass in the file content as environment variable java -Dusername=${cat /path/username} but I want to avoid putting my config outside the the spring properties file.
EDIT: The username and password are stored as plaintext in separate files.
Solution
You can’t read the contents of a file from Spring application properties file. But you can certainly configure the data source programmatically, and in code, read the files.
@Configuration
public class DataSourceConfig {
@Bean
public DataSource getDataSource() {
DataSourceBuilder dataSourceBuilder = DataSourceBuilder.create();
dataSourceBuilder.driverClassName("org.h2.Driver");
dataSourceBuilder.url("jdbc:h2:mem:test");
dataSourceBuilder.username("SA");
dataSourceBuilder.password("");
return dataSourceBuilder.build();
}
}
See this article for details. I’m assuming you know how to read a file using Spring Boot, if not, you can see this article.
Answered By - Abhijit Sarkar