【问题标题】:How to use a windows environment variable to hide an API key?如何使用 Windows 环境变量隐藏 API 密钥?
【发布时间】:2016-10-03 02:33:18
【问题描述】:

我有一个使用 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 密钥的一般答案。

【问题讨论】:

    标签: visual-studio asp.net-core environment-variables


    【解决方案1】:

    添加环境变量配置提供程序。来自here的示例:

    public Startup(IHostingEnvironment hostingEnvironment)
    {
        var builder = new ConfigurationBuilder()
            .SetBasePath(hostingEnvironment.ContentRootPath)
            .AddJsonFile("config.json")
            .AddEnvironmentVariables();
    }
    

    如果你只是想在开发过程中隐藏密钥,可以使用user secrets

    【讨论】:

      猜你喜欢
      • 2020-03-24
      • 2016-10-12
      • 2021-01-08
      • 1970-01-01
      • 2020-04-18
      • 2020-12-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多