Spring Boot — Hide your Credentials
This is my first article. As I was working on a personal project, I was wondering how to hide my credentials when pushing to git using Sprint Boot. It might be useful to some of you.
Hide Your Credentials From the Outside World
Reminder: .properties
files in Spring boot are config file.
Create a file to save your credentials 🗄
In your project root folder, create a env.properties
.
DB_DATABASE=NameofyourappSavedIntoYourDB
DB_USER=yourUsername
DB_PASSWORD=SuperStrongPassword
API_KEY=superkey
.gitignore
A gitignore file specifies intentionally untracked files that Git should ignore.
This file must be updated to include the file you would like to not publish. Example: file with Credentials.
In your .gitignore
file, add the name of the file you want to ignore, in this case: env.properties
.
Update your application.properties
File
As you need the variable from an other file, you need to import it.
🤓 ☝️ Explanations 🕶 :
spring.config
=> .properties files are from the spring configimport
=> action we want to dofile:
=> well, we specifiy the name of our file
1️⃣ Hence, you’ll need the following line: spring.config.import=file:env.properties
2️⃣ Then use your Environment variable freshly created in your env.properties file with ${ENV_VAR}
:
spring.datasource.url=jdbc:h2:file:~/${DB_DATABASE}
spring.datasource.username=${DB_USER}
spring.datasource.password=${DB_PASSWORD}
That’s it ! Your Turn!
###############################################################
⏱ Update:
As an update, since it has been a while since I published this article. You can also use environment variables.
Locally, adding your environment variables in your IDE Run Configuration before running your app.
Additionally, in terms of hiding credentials, I could recommend using sops and age in general. Techno Tim wrote an excellent introduction about it: Encrypt Your Sensitive Information Before Storing It — Encrypting with Mozilla SOPS and AGE