Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I handle a secret API Key when I push to GitHub so that my project is still functional when the repo is cloned?

I have a simple project that makes HTTP requests to an API endpoint and uses an API Key that I want to keep secret. Initially I put the key in its own file, imported the key into the file that uses it, and added the key file to the .gitignore. The problem is that this approach won't work if someone clones the GitHub repository.

So my question is - how can I keep my API key secret, but have my project still be functional if someone clones the repo?

Any feedback greatly appreciated.

like image 498
akorn3000 Avatar asked Oct 12 '18 18:10

akorn3000


People also ask

How do I hide API keys when pushing to GitHub?

The only way to hide it is to proxy your request through your own server. Netlify Functions are a free way to add some simple backend code to a frontend app. This is this method I used while learning to program in college, where I needed to share my progress with my peer group without disclosing my API keys.


1 Answers

Most importantly, you do not add it, ever. If you added it, committed it, and then removed it, it is still possible to recover it as a stranger with access to your repo by checking out the old commit.

With that out of the way, what you can do:

  • Prominently tell the user that they need to get and set up their own API key - and maybe even how to do so.
  • Add a check at the start of your software, that provides a helpful error message if the API key is missing, and otherwise starts your actual program
  • Add a dummy file to show how it should be set up. I did that for my telegram chatbot: never commit secret.config, but commit sample_secret.config so that anybody who forks your repository can see what syntax he would need to use. sample_secret.config is never used by the software, and instead of the API key contains a key like this-is-4-dummy-API-key-3232 or whatever makes sense.
  • Create a second API key which works but which can be abused by the public without any issues. Set everything up so that it works with either API key, and only commit the second one.
like image 175
lucidbrot Avatar answered Oct 05 '22 23:10

lucidbrot