我有一个使用Google Maps API的Visual Studio 2015 ASP.NET Core 1.0项目。目前,我可以在两个地方对API密钥进行硬编码:
1)视图的脚本标记,例如
<script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY_HERE"></script>
2)项目的config.json文件,例如
{
"Keys": { "GoogleMapsAPIKey": "YOUR_API_KEY_HERE" }
}
使用源代码控制时,无论哪种方式都暴露了密钥,为什么不使用Windows环境变量?
在Windows系统属性中,我添加了一个名为GoogleMapsAPIKey的新环境变量,并粘贴在实际密钥中。
现在如何在脚本标记或config.json中使用此环境变量?
问题的目的是获得有关如何使用环境变量在这种情况下隐藏API密钥的一般答案。
答案 0 :(得分:1)
添加环境变量配置提供程序。 here的示例:
public Startup(IHostingEnvironment hostingEnvironment)
{
var builder = new ConfigurationBuilder()
.SetBasePath(hostingEnvironment.ContentRootPath)
.AddJsonFile("config.json")
.AddEnvironmentVariables();
}
如果您只想在开发过程中隐藏密钥,可以使用user secrets。