【问题标题】:Passing configurable appInsights key to javascript (react/angular) app将可配置的 appInsights 密钥传递给 javascript (react/angular) 应用程序
【发布时间】:2019-11-21 07:20:08
【问题描述】:

我正在将 Azure AppInsights 与一些 ASP.NET Core 2.1 应用程序一起使用。我将检测密钥保存在 appsettings.json 中(后来被 Azure 应用服务中的应用配置覆盖)。显然,密钥可能因环境而异(在 dev/qa/prod 环境中不同)。 AppInsights SDK 在后端使用该密钥。

我的问题是:如何将该密钥传递给 JavaScript/React 应用程序(以将其与 JavaScript App Insisghts sdk 一起使用)?我没有使用 Razor(我不想)来生成主页 - 它只是静态 html 页面:

<!DOCTYPE html>
<html>
<head>
    <title>To Do List</title>
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">

    <script type="text/javascript">
         var appInsights=window.appInsights||function(a){
             function b(a){c[a]=function(){var b=arguments;c.queue.push(function(){c[a].apply(c,b)})}}var c={config:a},d=document,e=window;setTimeout(function(){var b=d.createElement("script");b.src=a.url||"https://az416426.vo.msecnd.net/scripts/a/ai.0.js",d.getElementsByTagName("script")[0].parentNode.appendChild(b)});try{c.cookie=d.cookie}catch(a){}c.queue=[];for(var f=["Event","Exception","Metric","PageView","Trace","Dependency"];f.length;)b("track"+f.pop());if(b("setAuthenticatedUserContext"),b("clearAuthenticatedUserContext"),b("startTrackEvent"),b("stopTrackEvent"),b("startTrackPage"),b("stopTrackPage"),b("flush"),!a.disableExceptionTracking){f="onerror",b("_"+f);var g=e[f];e[f]=function(a,b,d,e,h){var i=g&&g(a,b,d,e,h);return!0!==i&&c["_"+f](a,b,d,e,h),i}}return c
         }({
             instrumentationKey: "how_to_populate_that_key?"
         });
         window.appInsights=appInsights,appInsights.queue&&0===appInsights.queue.length&&appInsights.trackPageView();
    </script>

</head>
  <body>
    <div id="root"></div>
  </body>
</html>

将密钥从后端动态传递到前端的正确解决方案是什么?这应该被某个端点公开吗?或者我应该以某种方式在后端动态生成某种脚本(包含该键)并引用它 index.html?

我只是不想在 JS 代码库中硬编码密钥。

【问题讨论】:

    标签: javascript asp.net-core azure-application-insights


    【解决方案1】:

    在应用加载之前调用 API 并加载 Instrumentation Key,或者这是从后端加载的另一种方式

    <script type="text/javascript">
    // Standard Application Insights web page script:
    var appInsights = window.appInsights || function(config){ ...
    // Modify this part:
    }({instrumentationKey:  
      // Generate from server property:
      "@Microsoft.ApplicationInsights.Extensibility.TelemetryConfiguration.Active.InstrumentationKey"
      }
     )
    </script>
    

    欲了解更多信息,请通过此https://docs.microsoft.com/en-us/azure/azure-monitor/app/separate-resources#web-pages

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-01-21
      • 2017-09-22
      • 1970-01-01
      • 1970-01-01
      • 2021-11-15
      • 2018-01-25
      • 1970-01-01
      相关资源
      最近更新 更多