How to remove Hard-Coded Credentials from code in GoLang
There’s a password on my code! 😱
You might be wondering why you should remove hard-coded credentials from your code since only you or your team will have access to it. I’m sorry to break it to you but, actually, hard-coded credentials could be categorised as the second most common security vulnerability according to OWASP’s Top 10 Application Security Risks, fitting under the A2:2017-Broken Authentication topic. Don’t make it easier for the bad guys!
Let’s get started!
To begin with, your code might be looking something like this, with credentials or sensitive information showing in plain text, just like in the image below:
When running the code we have the following result:
Worry not, friend, with godotenv library we’ll be able to remove all credentials from the code in no time!
The idea here is to create a .env
file to keep all the sensitive information your code might need. With this file, your code will only have placeholders instead of clear text credentials. It’s common practice to keep this .env
file in your app’s root directory or in the same directory as your main.go
file.
In this case, I’ll name my .env
file as credentials.env
and it’s content is as follows:
To write a .env
file, you must place the name of your environment variable on the left, not necessarily in all caps, and their value on the right, only separated by a =
sign. In this kind of file, to write comments, simply add a#
and your desired text, as shown above. Empty lines are ignored.
Now that our .env
file is properly set up, it’s time to change our code!
We’ll need to add a new function, getEnvVars()
,to get our environment variables from credentials.env
, which basically loads our variables into our code through the godotenv.Load("NameOfTheFile.env")
method.
After that, in the main function, all we need to do is map our environment variables into normal variables through os.Getenv("YourVariableHere")
, as we can see from the image below:
Ok, our code looks good, but does it work?
As we can see from the image above, our code runs perfectly, and much more secure with no plain text credentials! 🔒
To make it even more secure, be sure to add .env
files to your .gitignore
file, so if you decide to add your code to GitHub your credentials won’t be added by accident. My .gitignore
file for this project is as follows:
If you would like to clone this example program, you can find it here on my GitHub.
Thanks to Douglas Adams for the excellent tips on the galaxy!
Thanks for reading! Feedback is appreciated!