防止 API 密钥被提交的最佳实践?
我正在开发 ac# 程序,该程序从 Web 服务检索信息,并使用 API 密钥进行身份验证。
目前,我在程序中硬编码了这个值,但由于我想将代码保存在公共 github 存储库中,因此我必须在提交之前手动删除它。
有什么更自动化的方法可以防止我意外地在 API 密钥仍在代码中的情况下进行提交?
我正在考虑创建一个脚本,添加在 Visual Studio 中使用构建前/构建后命令执行选项的秘密。这样我就不必将 API 密钥保留在代码中,并且在构建后它将被删除,因此永远不会发生意外提交的情况。
I am working on a c# program that retrieves information from a webservice and it uses an API key for authentication.
Currently I hardcoded this value in my program, but since I would like to keep the code in a public github repository I have to remove this by hand before committing it.
What is a more automated way of preventing me from accidentally committing with the API key still in the code?
I was thinking of creating a script that adds the secrets in using pre/post-build command execute options in Visual Studio. This way I never have to keep the API key in the code and it will be removed after building so committing it by accident will never happen.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
使用配置文件 或Windows 注册表。
我还建议对其进行加密,在 Windows 上您可以使用数据保护 API (DPAPI)。 .Net 2.0+ 有一个类调用 ProtectedData使用起来非常简单。这样,如果您确实提交了配置,密钥仍然是加密的,并且仅在您的计算机上有效,甚至仅适用于该计算机上的用户,具体取决于您的数据保护范围。不过,您需要提供某种方式让人们输入密钥以在他们的机器上使用。
Use a configuration file or the Windows Registry.
I'd also recommend encrypting it, on Windows you can use the Data Protection API (DPAPI). .Net 2.0+ has a class call ProtectedData that's very simple to use. This way if you do commit your configuration the key is still encrypted and will only work on your machine or even for your user on that machine depending on how you scope your data protection. You'll want to make some way for people to enter in a key to use on their machines though.
您可以将其添加到 web.config 并设置Web 配置转换通过选择适当的配置(调试、发布等)来构建项目时动态更改它。您可以使用它来用虚拟值替换密钥。
You can add it to your web.config and set up web config transformations to change it dynamically when you build the project by selecting the appropriate configuration (debug, release etc). You can use this to replace the key with a dummy value.