paint-brush
How to Hide Credentials in Spring Bootby@mamit
1,563 reads
1,563 reads

How to Hide Credentials in Spring Boot

by Amit TiwaryFebruary 24th, 2023
Read on Terminal Reader
Read this story w/o Javascript
tldt arrow

Too Long; Didn't Read

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. We know that we can add the variable in the application.properties file and then use it in the java code. But we can import a file in theApplication.properties and use the variables.
featured image - How to Hide Credentials in Spring Boot
Amit Tiwary HackerNoon profile picture

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


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


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


Also published here.