How to push code to Github hiding the API keys?

陌路散爱 提交于 2019-12-17 22:27:03

问题


I want to push some codes to my GitHub Repository. These codes are in different languages like Javascript, Java, Python etc. Some of those codes contain some private API key that I don't want to publish.

Is there any way to hide the keys automatically.? Should I remove it from my code manually.?

There are many projects that I want to push to GitHub. So, manual removal is not a good option.


回答1:


You should consider using .env files and read the keys from the environmental variables. How to do so depends on the language and tools you use (for node.js, php, etc.).

You can exclude .env file from commits by adding .env to the .gitignore. You can also upload an example configuration .env.example with dummy data or blanks to show the schema your application requires.




回答2:


Any time you have files with sensible data like

config.yml

you MUST NOT commit them in your repository. I'll show you an example.

Suppose you have a yaml file with some username and password:

# app/config/credentials.yml
credentials:
    username: foo
    password: bar

If you want to hide the foo and the bar values, remove this file from your repository, but add just a distribution file that aims to maintain username and password fields, but without real values:

# app/config/credentials.yml.dist
credentials:
    username: ~
    password: ~

During the installation you can get this file, copying app/config/credentials.yml.dist to app/config/credentials.yml.

Also, remember to add app/config/credentials.yml to your .gitignore file.

Its the same for api keys:

# app/config/config.yml
config:
    credentials:
        username: foo
        password: bar
    api_stuffs:
        api_foo: fooooo
        api_secret: baaaaar
        api_token: tooooken

This works for configuration files, and is a good pattern that saves you every time you need to share the structure of a configuration but not sensible data. Ini files, configurations and so on.




回答3:


Having your API key in the code is probably a bad idea anyway. It means that anyone else that wants to use your code will have to edit the code and rebuild it.

The textbook solution for such usecases is to move the credentials to some configuration file, and add clear documentation in the README.md file about how the configuration file's structure and location. You could also add an entry for it in your gitignore file to prevent yourself (and anyone else) from pushing your private information to GitHub by mistake.




回答4:


You can add enviornment variables in your server to hide your API keys. All popular programming languages have default methods to acess the enviornment variables.



来源:https://stackoverflow.com/questions/44342276/how-to-push-code-to-github-hiding-the-api-keys

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!