DEV Community

Cover image for Hide credentials in spring boot
Amit Tiwary
Amit Tiwary

Posted on • Updated on

Hide credentials in spring boot

Spring boot make it easy to create spring applications. It makes it easier and faster to set up, configure and run the web application. When I was working on one of the projects, I was required to use some credentials. But I can't use it directly in the code. It should be hidden and still accessible in the code. We know that we can add the variable in the application.properties file and then use it in the java code. But I was not ablw to find how can add the env variable in a file and then access it in the application.properties file. If variables can be added in a file and accessed in the application.properties then the file can be included in the gitignore, and code can be pushed to github and shared with others without exposing the credential.

So I did research and find out that we can import a file in the application.properties and use the variables. We are going to use the env.properties file to save the credentials. Create a env.properties file. I created this file in the resources folder, so that I can easily access in the application.properties.

folder to save the env.properties
Add some credentials in the env.properties file like

DB_USER=name_of_sql_db_user
DB_DATABASE_NAME=name_of_database
DB_PASSWORD=database_password
GOOGLE_API_KEY=google_api_credential
Enter fullscreen mode Exit fullscreen mode

These are the secret info and can't be shared with everyone. But it is required to connect with the database server or to use the google service.

Now to access these variables in our java file, we have to import these variables in the application.properties file. Import the env.properties file so that we can get these variables in the application.properties file.

spring.config.import = env.properties
spring.datasource.username = DB_USER
Enter fullscreen mode Exit fullscreen mode

env.properties file is in the same folder with the application.properties so it can be imported directly using the file name. We are telling the code to use the config from the import file i.e from env.properties.

Now to make sure that the credentials is not commited and pushed to github, we have to make sure that env.properties file is included in .gitignore.

/src/main/resources/env.properties
Enter fullscreen mode Exit fullscreen mode

Latest comments (1)

Collapse
 
gitpeters profile image
Peter Abraham

This was very helpful. Thank you.

You'd like to correct your spring.config.import :)