Tuesday, 30 July 2024

Microsoft Entra authentication for Application Insights

 

Microsoft Entra authentication for Application Insights

Application Insights now supports Microsoft Entra authentication. By using Microsoft Entra ID, you can ensure that only authenticated telemetry is ingested in your Application Insights resources.

Using various authentication systems can be cumbersome and risky because it's difficult to manage credentials at scale. You can now choose to opt out of local authentication to ensure only telemetry exclusively authenticated by using managed identities and Microsoft Entra ID is ingested in your resource. This feature is a step to enhance the security and reliability of the telemetry used to make critical operational (alerting and autoscaling) and business decisions.

Prerequisites

The following preliminary steps are required to enable Microsoft Entra authenticated ingestion. You need to:

Unsupported scenarios

The following Software Development Kits (SDKs) and features are unsupported for use with Microsoft Entra authenticated ingestion:

Configure and enable Microsoft Entra ID-based authentication

  1. If you don't already have an identity, create one by using either a managed identity or a service principal.

  2. Assign the required Role-based access control (RBAC) role to the Azure identity, service principal, or Azure user account.

    Follow the steps in Assign Azure roles to add the Monitoring Metrics Publisher role to the expected identity, service principal, or Azure user account by setting the target Application Insights resource as the role scope.

     Note

    Although the Monitoring Metrics Publisher role says "metrics," it will publish all telemetry to the Application Insights resource.

  3. Follow the configuration guidance in accordance with the language that follows.

 Note

Support for Microsoft Entra ID in the Application Insights .NET SDK is included starting with version 2.18-Beta3.

Application Insights .NET SDK supports the credential classes provided by Azure Identity.

  • We recommend DefaultAzureCredential for local development.
  • Ensure you're authenticated on Visual Studio with the expected Azure user account. For more information, see Authenticate via Visual Studio.
  • We recommend ManagedIdentityCredential for system-assigned and user-assigned managed identities.
    • For system-assigned, use the default constructor without parameters.
    • For user-assigned, provide the client ID to the constructor.

The following example shows how to manually create and configure TelemetryConfiguration by using .NET:

C#
TelemetryConfiguration.Active.ConnectionString = "InstrumentationKey=00000000-0000-0000-0000-000000000000;IngestionEndpoint=https://xxxx.applicationinsights.azure.com/";
var credential = new DefaultAzureCredential();
TelemetryConfiguration.Active.SetAzureTokenCredential(credential);

The following example shows how to configure TelemetryConfiguration by using .NET Core:

C#
services.Configure<TelemetryConfiguration>(config =>
{
       var credential = new DefaultAzureCredential();
       config.SetAzureTokenCredential(credential);
});
services.AddApplicationInsightsTelemetry(new ApplicationInsightsServiceOptions
{
    ConnectionString = "InstrumentationKey=00000000-0000-0000-0000-000000000000;IngestionEndpoint=https://xxxx.applicationinsights.azure.com/"
});

Query Application Insights using Microsoft Entra authentication

You can submit a query request by using the Azure Monitor Application Insights endpoint https://api.applicationinsights.io. To access the endpoint, you must authenticate through Microsoft Entra ID.

Set up authentication

To access the API, you register a client app with Microsoft Entra ID and request a token.

  1. Register an app in Microsoft Entra ID.

  2. On the app's overview page, select API permissions.

  3. Select Add a permission.

  4. On the APIs my organization uses tab, search for Application Insights and select Application Insights API from the list.

  5. Select Delegated permissions.

  6. Select the Data.Read checkbox.

  7. Select Add permissions.

Now that your app is registered and has permissions to use the API, grant your app access to your Application Insights resource.

  1. From your Application Insights resource overview page, select Access control (IAM).

  2. Select Add role assignment.

  3. Select the Reader role and then select Members.

  4. On the Members tab, choose Select members.

  5. Enter the name of your app in the Select box.

  6. Select your app and choose Select.

  7. Select Review + assign.

  8. After you finish the Active Directory setup and permissions, request an authorization token.


Request an authorization token

Before you begin, make sure you have all the values required to make the request successfully. All requests require:

  • Your Microsoft Entra tenant ID.
  • Your App Insights App ID - If you're currently using API Keys, it's the same app ID.
  • Your Microsoft Entra client ID for the app.
  • A Microsoft Entra client secret for the app.

The Application Insights API supports Microsoft Entra authentication with three different Microsoft Entra ID OAuth2 flows:

  • Client credentials
  • Authorization code
  • Implicit

Client credentials flow

In the client credentials flow, the token is used with the Application Insights endpoint. A single request is made to receive a token by using the credentials provided for your app in the previous step when you register an app in Microsoft Entra ID.

Use the https://api.applicationinsights.io endpoint.

Client credentials token URL (POST request)
HTTP
    POST /<your-tenant-id>/oauth2/token
    Host: https://login.microsoftonline.com
    Content-Type: application/x-www-form-urlencoded
    
    grant_type=client_credentials
    &client_id=<app-client-id>
    &resource=https://api.applicationinsights.io
    &client_secret=<app-client-secret>

A successful request receives an access token in the response:

HTTP
    {
        token_type": "Bearer",
        "expires_in": "86399",
        "ext_expires_in": "86399",
        "access_token": ""eyJ0eXAiOiJKV1QiLCJ.....Ax"
    }

Use the token in requests to the Application Insights endpoint:

HTTP
    POST /v1/apps/yous_app_id/query?timespan=P1D
    Host: https://api.applicationinsights.io
    Content-Type: application/json
    Authorization: Bearer <your access token>

    Body:
    {
    "query": "requests | take 10"
    }

Example response:

{
  "tables": [
    {
      "name": "PrimaryResult",
      "columns": [
        {
          "name": "timestamp",
          "type": "datetime"
        },
        {
          "name": "id",
          "type": "string"
        },
        {
          "name": "source",
          "type": "string"
        },
        {
          "name": "name",
          "type": "string"
        },
        {
          "name": "url",
          "type": "string"
        },
        {
          "name": "success",
          "type": "string"
        },
        {
          "name": "resultCode",
          "type": "string"
        },
        {
          "name": "duration",
          "type": "real"
        },
        {
          "name": "performanceBucket",
          "type": "string"
        },
        {
          "name": "customDimensions",
          "type": "dynamic"
        },
        {
          "name": "customMeasurements",
          "type": "dynamic"
        },
        {
          "name": "operation_Name",
          "type": "string"
        },
        {
          "name": "operation_Id",
          "type": "string"
        },
        {
          "name": "operation_ParentId",
          "type": "string"
        },
        {
          "name": "operation_SyntheticSource",
          "type": "string"
        },
        {
          "name": "session_Id",
          "type": "string"
        },
        {
          "name": "user_Id",
          "type": "string"
        },
        {
          "name": "user_AuthenticatedId",
          "type": "string"
        },
        {
          "name": "user_AccountId",
          "type": "string"
        },
        {
          "name": "application_Version",
          "type": "string"
        },
        {
          "name": "client_Type",
          "type": "string"
        },
        {
          "name": "client_Model",
          "type": "string"
        },
        {
          "name": "client_OS",
          "type": "string"
        },
        {
          "name": "client_IP",
          "type": "string"
        },
        {
          "name": "client_City",
          "type": "string"
        },
        {
          "name": "client_StateOrProvince",
          "type": "string"
        },
        {
          "name": "client_CountryOrRegion",
          "type": "string"
        },
        {
          "name": "client_Browser",
          "type": "string"
        },
        {
          "name": "cloud_RoleName",
          "type": "string"
        },
        {
          "name": "cloud_RoleInstance",
          "type": "string"
        },
        {
          "name": "appId",
          "type": "string"
        },
        {
          "name": "appName",
          "type": "string"
        },
        {
          "name": "iKey",
          "type": "string"
        },
        {
          "name": "sdkVersion",
          "type": "string"
        },
        {
          "name": "itemId",
          "type": "string"
        },
        {
          "name": "itemType",
          "type": "string"
        },
        {
          "name": "itemCount",
          "type": "int"
        }
      ],
      "rows": [
        [
          "2018-02-01T17:33:09.788Z",
          "|0qRud6jz3k0=.c32c2659_",
          null,
          "GET Reports/Index",
          "http://fabrikamfiberapp.azurewebsites.net/Reports",
          "True",
          "200",
          "3.3833",
          "<250ms",
          "{\"_MS.ProcessedByMetricExtractors\":\"(Name:'Requests', Ver:'1.0')\"}",
          null,
          "GET Reports/Index",
          "0qRud6jz3k0=",
          "0qRud6jz3k0=",
          "Application Insights Availability Monitoring",
          "9fc6738d-7e26-44f0-b88e-6fae8ccb6b26",
          "us-va-ash-azr_9fc6738d-7e26-44f0-b88e-6fae8ccb6b26",
          null,
          null,
          "AutoGen_49c3aea0-4641-4675-93b5-55f7a62d22d3",
          "PC",
          null,
          null,
          "52.168.8.0",
          "Boydton",
          "Virginia",
          "United States",
          null,
          "fabrikamfiberapp",
          "RD00155D5053D1",
          "cf58dcfd-0683-487c-bc84-048789bca8e5",
          "fabrikamprod",
          "5a2e4e0c-e136-4a15-9824-90ba859b0a89",
          "web:2.5.0-33031",
          "051ad4ef-0776-11e8-ac6e-e30599af6943",
          "request",
          "1"
        ],
        [
          "2018-02-01T17:33:15.786Z",
          "|x/Ysh+M1TfU=.c32c265a_",
          null,
          "GET Home/Index",
          "http://fabrikamfiberapp.azurewebsites.net/",
          "True",
          "200",
          "716.2912",
          "500ms-1sec",
          "{\"_MS.ProcessedByMetricExtractors\":\"(Name:'Requests', Ver:'1.0')\"}",
          null,
          "GET Home/Index",
          "x/Ysh+M1TfU=",
          "x/Ysh+M1TfU=",
          "Application Insights Availability Monitoring",
          "58b15be6-d1e6-4d89-9919-52f63b840913",
          "emea-se-sto-edge_58b15be6-d1e6-4d89-9919-52f63b840913",
          null,
          null,
          "AutoGen_49c3aea0-4641-4675-93b5-55f7a62d22d3",
          "PC",
          null,
          null,
          "51.141.32.0",
          "Cardiff",
          "Cardiff",
          "United Kingdom",
          null,
          "fabrikamfiberapp",
          "RD00155D5053D1",
          "cf58dcfd-0683-487c-bc84-048789bca8e5",
          "fabrikamprod",
          "5a2e4e0c-e136-4a15-9824-90ba859b0a89",
          "web:2.5.0-33031",
          "051ad4f0-0776-11e8-ac6e-e30599af6943",
          "request",
          "1"
        ]
      ]
    }
  ]
}

Authorization code flow

The main OAuth2 flow supported is through authorization codes. This method requires two HTTP requests to acquire a token with which to call the Azure Monitor Application Insights API. There are two URLs, with one endpoint per request. Their formats are described in the following sections.

Authorization code URL (GET request)
HTTP
    GET https://login.microsoftonline.com/YOUR_Azure AD_TENANT/oauth2/authorize?
    client_id=<app-client-id>
    &response_type=code
    &redirect_uri=<app-redirect-uri>
    &resource=https://api.applicationinsights.io

When a request is made to the authorized URL, the client_id is the application ID from your Microsoft Entra app, copied from the app's properties menu. The redirect_uri is the homepage/login URL from the same Microsoft Entra app. When a request is successful, this endpoint redirects you to the sign-in page you provided at sign-up with the authorization code appended to the URL. See the following example:

HTTP
    http://<app-client-id>/?code=AUTHORIZATION_CODE&session_state=STATE_GUID

At this point, you obtain an authorization code, which you now use to request an access token.

Authorization code token URL (POST request)
HTTP
    POST /YOUR_Azure AD_TENANT/oauth2/token HTTP/1.1
    Host: https://login.microsoftonline.com
    Content-Type: application/x-www-form-urlencoded
    
    grant_type=authorization_code
    &client_id=<app client id>
    &code=<auth code fom GET request>
    &redirect_uri=<app-client-id>
    &resource=https://api.applicationinsights.io
    &client_secret=<app-client-secret>

All values are the same as before, with some additions. The authorization code is the same code you received in the previous request after a successful redirect. The code is combined with the key obtained from the Microsoft Entra app. If you didn't save the key, you can delete it and create a new one from the keys tab of the Microsoft Entra app menu. The response is a JSON string that contains the token with the following schema. Types are indicated for the token values.

Response example:

HTTP
    {
        "access_token": "eyJ0eXAiOiJKV1QiLCJ.....Ax",
        "expires_in": "3600",
        "ext_expires_in": "1503641912",
        "id_token": "not_needed_for_app_insights",
        "not_before": "1503638012",
        "refresh_token": "eyJ0esdfiJKV1ljhgYF.....Az",
        "resource": "https://api.applicationinsights.io",
        "scope": "Data.Read",
        "token_type": "bearer"
    }

The access token portion of this response is what you present to the Application Insights API in the Authorization: Bearer header. You can also use the refresh token in the future to acquire a new access_token and refresh_token when yours go stale. For this request, the format and endpoint are:

HTTP
    POST /YOUR_AAD_TENANT/oauth2/token HTTP/1.1
    Host: https://login.microsoftonline.com
    Content-Type: application/x-www-form-urlencoded
    
    client_id=<app-client-id>
    &refresh_token=<refresh-token>
    &grant_type=refresh_token
    &resource=https://api.applicationinsights.io
    &client_secret=<app-client-secret>

Response example:

HTTP
    {
      "token_type": "Bearer",
      "expires_in": "3600",
      "expires_on": "1460404526",
      "resource": "https://api.applicationinsights.io",
      "access_token": "eyJ0eXAiOiJKV1QiLCJ.....Ax",
      "refresh_token": "eyJ0esdfiJKV1ljhgYF.....Az"
    }

Implicit code flow

The Application Insights API supports the OAuth2 implicit flow. For this flow, only a single request is required, but no refresh token can be acquired.

Implicit code authorization URL
HTTP
    GET https://login.microsoftonline.com/YOUR_AAD_TENANT/oauth2/authorize?
    client_id=<app-client-id>
    &response_type=token
    &redirect_uri=<app-redirect-uri>
    &resource=https://api.applicationinsights.io

A successful request produces a redirect to your redirect URI with the token in the URL:

HTTP
    http://YOUR_REDIRECT_URI/#access_token=YOUR_ACCESS_TOKEN&token_type=Bearer&expires_in=3600&session_state=STATE_GUID

This access_token serves as the Authorization: Bearer header value when it passes to the Application Insights API to authorize requests.

Disable local authentication

After the Microsoft Entra authentication is enabled, you can choose to disable local authentication. This configuration allows you to ingest telemetry authenticated exclusively by Microsoft Entra ID and affects data access (for example, through API keys).

You can disable local authentication by using the Azure portal or Azure Policy or programmatically.

Azure portal

  1. From your Application Insights resource, select Properties under Configure in the menu on the left. Select Enabled (click to change) if the local authentication is enabled.

    Screenshot that shows Properties under the Configure section and the Enabled (select to change) local authentication button.

  2. Select Disabled and apply changes.

    Screenshot that shows local authentication with the Enabled/Disabled button.

  3. After disabling local authentication on your resource, you'll see the corresponding information in the Overview pane.

    Screenshot that shows the Overview tab with the Disabled (select to change) local authentication button.

Azure Policy

Azure Policy for DisableLocalAuth denies users the ability to create a new Application Insights resource without this property set to true. The policy name is Application Insights components should block non-AAD auth ingestion.

To apply this policy definition to your subscription, create a new policy assignment and assign the policy.

The following example shows the policy template definition:

JSON
{
    "properties": {
        "displayName": "Application Insights components should block non-AAD auth ingestion",
        "policyType": "BuiltIn",
        "mode": "Indexed",
        "description": "Improve Application Insights security by disabling log ingestion that are not AAD-based.",
        "metadata": {
            "version": "1.0.0",
            "category": "Monitoring"
        },
        "parameters": {
            "effect": {
                "type": "String",
                "metadata": {
                    "displayName": "Effect",
                    "description": "The effect determines what happens when the policy rule is evaluated to match"
                },
                "allowedValues": [
                    "audit",
                    "deny",
                    "disabled"
                ],
                "defaultValue": "audit"
            }
        },
        "policyRule": {
            "if": {
                "allOf": [
                    {
                        "field": "type",
                        "equals": "Microsoft.Insights/components"
                    },
                    {
                        "field": "Microsoft.Insights/components/DisableLocalAuth",
                        "notEquals": "true"                        
                    }
                ]
            },
            "then": {
                "effect": "[parameters('effect')]"
            }
        }
    }
}

Programmatic enablement

The property DisableLocalAuth is used to disable any local authentication on your Application Insights resource. When this property is set to true, it enforces that Microsoft Entra authentication must be used for all access.

The following example shows the Azure Resource Manager template you can use to create a workspace-based Application Insights resource with LocalAuth disabled.

JSON
{
    "$schema": "http://schema.management.azure.com/schemas/2015-01-01/deploymentTemplate.json#",
    "contentVersion": "1.0.0.0",
    "parameters": {
        "name": {
            "type": "string"
        },
        "type": {
            "type": "string"
        },
        "regionId": {
            "type": "string"
        },
        "tagsArray": {
            "type": "object"
        },
        "requestSource": {
            "type": "string"
        },
        "workspaceResourceId": {
            "type": "string"
        },
        "disableLocalAuth": {
            "type": "bool"
        }
     
    },
    "resources": [
        {
        "name": "[parameters('name')]",
        "type": "microsoft.insights/components",
        "location": "[parameters('regionId')]",
        "tags": "[parameters('tagsArray')]",
        "apiVersion": "2020-02-02-preview",
        "dependsOn": [],
        "properties": {
            "Application_Type": "[parameters('type')]",
            "Flow_Type": "Redfield",
            "Request_Source": "[parameters('requestSource')]",
            "WorkspaceResourceId": "[parameters('workspaceResourceId')]",
            "DisableLocalAuth": "[parameters('disableLocalAuth')]"
            }
    }
 ]
}

Enable Azure Monitor Application Insights Real User Monitoring

 

Enable Azure Monitor Application Insights Real User Monitoring

The Microsoft Azure Monitor Application Insights JavaScript SDK collects usage data, which allows you to monitor and analyze the performance of JavaScript web applications. This is commonly referred to as Real User Monitoring or RUM.

The Application Insights JavaScript SDK has a base SDK and several plugins for more capabilities.

Conceptual diagram that shows the Application Insights JavaScript SDK, its plugins/extensions, and their relationship to each other.

We collect page views by default. But if you want to also collect clicks by default, consider adding the Click Analytics Auto-Collection plug-in:

We provide the Debug plugin and Performance plugin for debugging/testing. In rare cases, it's possible to build your own extension by adding a custom plugin.

Prerequisites

Get started

Follow the steps in this section to instrument your application with the Application Insights JavaScript SDK.

 Tip

Good news! We're making it even easier to enable JavaScript. Check out where JavaScript (Web) SDK Loader Script injection by configuration is available!

Add the JavaScript code

Two methods are available to add the code to enable Application Insights via the Application Insights JavaScript SDK:

MethodWhen would I use this method?
JavaScript (Web) SDK Loader ScriptFor most customers, we recommend the JavaScript (Web) SDK Loader Script because you never have to update the SDK and you get the latest updates automatically. Also, you have control over which pages you add the Application Insights JavaScript SDK to.
npm packageYou want to bring the SDK into your code and enable IntelliSense. This option is only needed for developers who require more custom events and configuration. This method is required if you plan to use the React, React Native, or Angular Framework Extension.
  1. Paste the JavaScript (Web) SDK Loader Script at the top of each page for which you want to enable Application Insights.

    Preferably, you should add it as the first script in your <head> section so that it can monitor any potential issues with all of your dependencies.

    If Internet Explorer 8 is detected, JavaScript SDK v2.x is automatically loaded.

    HTML
    <script type="text/javascript">
    !(function (cfg){function e(){cfg.onInit&&cfg.onInit(n)}var x,w,D,t,E,n,C=window,O=document,b=C.location,q="script",I="ingestionendpoint",L="disableExceptionTracking",j="ai.device.";"instrumentationKey"[x="toLowerCase"](),w="crossOrigin",D="POST",t="appInsightsSDK",E=cfg.name||"appInsights",(cfg.name||C[t])&&(C[t]=E),n=C[E]||function(g){var f=!1,m=!1,h={initialize:!0,queue:[],sv:"8",version:2,config:g};function v(e,t){var n={},i="Browser";function a(e){e=""+e;return 1===e.length?"0"+e:e}return n[j+"id"]=i[x](),n[j+"type"]=i,n["ai.operation.name"]=b&&b.pathname||"_unknown_",n["ai.internal.sdkVersion"]="javascript:snippet_"+(h.sv||h.version),{time:(i=new Date).getUTCFullYear()+"-"+a(1+i.getUTCMonth())+"-"+a(i.getUTCDate())+"T"+a(i.getUTCHours())+":"+a(i.getUTCMinutes())+":"+a(i.getUTCSeconds())+"."+(i.getUTCMilliseconds()/1e3).toFixed(3).slice(2,5)+"Z",iKey:e,name:"Microsoft.ApplicationInsights."+e.replace(/-/g,"")+"."+t,sampleRate:100,tags:n,data:{baseData:{ver:2}},ver:undefined,seq:"1",aiDataContract:undefined}}var n,i,t,a,y=-1,T=0,S=["js.monitor.azure.com","js.cdn.applicationinsights.io","js.cdn.monitor.azure.com","js0.cdn.applicationinsights.io","js0.cdn.monitor.azure.com","js2.cdn.applicationinsights.io","js2.cdn.monitor.azure.com","az416426.vo.msecnd.net"],o=g.url||cfg.src,r=function(){return s(o,null)};function s(d,t){if((n=navigator)&&(~(n=(n.userAgent||"").toLowerCase()).indexOf("msie")||~n.indexOf("trident/"))&&~d.indexOf("ai.3")&&(d=d.replace(/(\/)(ai\.3\.)([^\d]*)$/,function(e,t,n){return t+"ai.2"+n})),!1!==cfg.cr)for(var e=0;e<S.length;e++)if(0<d.indexOf(S[e])){y=e;break}var n,i=function(e){var a,t,n,i,o,r,s,c,u,l;h.queue=[],m||(0<=y&&T+1<S.length?(a=(y+T+1)%S.length,p(d.replace(/^(.*\/\/)([\w\.]*)(\/.*)$/,function(e,t,n,i){return t+S[a]+i})),T+=1):(f=m=!0,s=d,!0!==cfg.dle&&(c=(t=function(){var e,t={},n=g.connectionString;if(n)for(var i=n.split(";"),a=0;a<i.length;a++){var o=i[a].split("=");2===o.length&&(t[o[0][x]()]=o[1])}return t[I]||(e=(n=t.endpointsuffix)?t.location:null,t[I]="https://"+(e?e+".":"")+"dc."+(n||"services.visualstudio.com")),t}()).instrumentationkey||g.instrumentationKey||"",t=(t=(t=t[I])&&"/"===t.slice(-1)?t.slice(0,-1):t)?t+"/v2/track":g.endpointUrl,t=g.userOverrideEndpointUrl||t,(n=[]).push((i="SDK LOAD Failure: Failed to load Application Insights SDK script (See stack for details)",o=s,u=t,(l=(r=v(c,"Exception")).data).baseType="ExceptionData",l.baseData.exceptions=[{typeName:"SDKLoadFailed",message:i.replace(/\./g,"-"),hasFullStack:!1,stack:i+"\nSnippet failed to load ["+o+"] -- Telemetry is disabled\nHelp Link: https://go.microsoft.com/fwlink/?linkid=2128109\nHost: "+(b&&b.pathname||"_unknown_")+"\nEndpoint: "+u,parsedStack:[]}],r)),n.push((l=s,i=t,(u=(o=v(c,"Message")).data).baseType="MessageData",(r=u.baseData).message='AI (Internal): 99 message:"'+("SDK LOAD Failure: Failed to load Application Insights SDK script (See stack for details) ("+l+")").replace(/\"/g,"")+'"',r.properties={endpoint:i},o)),s=n,c=t,JSON&&((u=C.fetch)&&!cfg.useXhr?u(c,{method:D,body:JSON.stringify(s),mode:"cors"}):XMLHttpRequest&&((l=new XMLHttpRequest).open(D,c),l.setRequestHeader("Content-type","application/json"),l.send(JSON.stringify(s)))))))},a=function(e,t){m||setTimeout(function(){!t&&h.core||i()},500),f=!1},p=function(e){var n=O.createElement(q),e=(n.src=e,t&&(n.integrity=t),n.setAttribute("data-ai-name",E),cfg[w]);return!e&&""!==e||"undefined"==n[w]||(n[w]=e),n.onload=a,n.onerror=i,n.onreadystatechange=function(e,t){"loaded"!==n.readyState&&"complete"!==n.readyState||a(0,t)},cfg.ld&&cfg.ld<0?O.getElementsByTagName("head")[0].appendChild(n):setTimeout(function(){O.getElementsByTagName(q)[0].parentNode.appendChild(n)},cfg.ld||0),n};p(d)}cfg.sri&&(n=o.match(/^((http[s]?:\/\/.*\/)\w+(\.\d+){1,5})\.(([\w]+\.){0,2}js)$/))&&6===n.length?(d="".concat(n[1],".integrity.json"),i="@".concat(n[4]),l=window.fetch,t=function(e){if(!e.ext||!e.ext[i]||!e.ext[i].file)throw Error("Error Loading JSON response");var t=e.ext[i].integrity||null;s(o=n[2]+e.ext[i].file,t)},l&&!cfg.useXhr?l(d,{method:"GET",mode:"cors"}).then(function(e){return e.json()["catch"](function(){return{}})}).then(t)["catch"](r):XMLHttpRequest&&((a=new XMLHttpRequest).open("GET",d),a.onreadystatechange=function(){if(a.readyState===XMLHttpRequest.DONE)if(200===a.status)try{t(JSON.parse(a.responseText))}catch(e){r()}else r()},a.send())):o&&r();try{h.cookie=O.cookie}catch(k){}function e(e){for(;e.length;)!function(t){h[t]=function(){var e=arguments;f||h.queue.push(function(){h[t].apply(h,e)})}}(e.pop())}var c,u,l="track",d="TrackPage",p="TrackEvent",l=(e([l+"Event",l+"PageView",l+"Exception",l+"Trace",l+"DependencyData",l+"Metric",l+"PageViewPerformance","start"+d,"stop"+d,"start"+p,"stop"+p,"addTelemetryInitializer","setAuthenticatedUserContext","clearAuthenticatedUserContext","flush"]),h.SeverityLevel={Verbose:0,Information:1,Warning:2,Error:3,Critical:4},(g.extensionConfig||{}).ApplicationInsightsAnalytics||{});return!0!==g[L]&&!0!==l[L]&&(e(["_"+(c="onerror")]),u=C[c],C[c]=function(e,t,n,i,a){var o=u&&u(e,t,n,i,a);return!0!==o&&h["_"+c]({message:e,url:t,lineNumber:n,columnNumber:i,error:a,evt:C.event}),o},g.autoExceptionInstrumented=!0),h}(cfg.cfg),(C[E]=n).queue&&0===n.queue.length?(n.queue.push(e),n.trackPageView({})):e();})({
      src: "https://js.monitor.azure.com/scripts/b/ai.3.gbl.min.js",
      // name: "appInsights", // Global SDK Instance name defaults to "appInsights" when not supplied
      // ld: 0, // Defines the load delay (in ms) before attempting to load the sdk. -1 = block page load and add to head. (default) = 0ms load after timeout,
      // useXhr: 1, // Use XHR instead of fetch to report failures (if available),
      // dle: true, // Prevent the SDK from reporting load failure log
      crossOrigin: "anonymous", // When supplied this will add the provided value as the cross origin attribute on the script tag
      // onInit: null, // Once the application insights instance has loaded and initialized this callback function will be called with 1 argument -- the sdk instance (DON'T ADD anything to the sdk.queue -- As they won't get called)
      // sri: false, // Custom optional value to specify whether fetching the snippet from integrity file and do integrity check
      cfg: { // Application Insights Configuration
        connectionString: "YOUR_CONNECTION_STRING"
    }});
    </script>
    
  2. (Optional) Add or update optional JavaScript (Web) SDK Loader Script configuration, if you need to optimize the loading of your web page or resolve loading errors.

    Screenshot of the JavaScript (Web) SDK Loader Script. The parameters for configuring the JavaScript (Web) SDK Loader Script are highlighted.

JavaScript (Web) SDK Loader Script configuration

NameTypeRequired?Description
srcstringRequiredThe full URL for where to load the SDK from. This value is used for the "src" attribute of a dynamically added <script /> tag. You can use the public CDN location or your own privately hosted one.
namestringOptionalThe global name for the initialized SDK. Use this setting if you need to initialize two different SDKs at the same time.

The default value is appInsights, so window.appInsights is a reference to the initialized instance.

Note: If you assign a name value or if a previous instance is assigned to the global name appInsightsSDK, the SDK initialization code requires it to be in the global namespace as window.appInsightsSDK=<name value> to ensure the correct JavaScript (Web) SDK Loader Script skeleton, and proxy methods are initialized and updated.
ldnumber in msOptionalDefines the load delay to wait before attempting to load the SDK. Use this setting when the HTML page is failing to load because the JavaScript (Web) SDK Loader Script is loading at the wrong time.

The default value is 0ms after timeout. If you use a negative value, the script tag is immediately added to the <head> region of the page and blocks the page load event until the script is loaded or fails.
useXhrbooleanOptionalThis setting is used only for reporting SDK load failures. For example, this setting is useful when the JavaScript (Web) SDK Loader Script is preventing the HTML page from loading, causing fetch() to be unavailable.

Reporting first attempts to use fetch() if available and then fallback to XHR. Set this setting to true to bypass the fetch check. This setting is necessary only in environments where fetch cannot transmit failure events, for example, when the JavaScript (Web) SDK Loader Script fails to load successfully.
crossOriginstringOptionalBy including this setting, the script tag added to download the SDK includes the crossOrigin attribute with this string value. Use this setting when you need to provide support for CORS. When not defined (the default), no crossOrigin attribute is added. Recommended values aren't defined (the default), "", or "anonymous". For all valid values, see the cross origin HTML attribute documentation.
onInitfunction(aiSdk) { ... }OptionalThis callback function is called after the main SDK script is successfully loaded and initialized from the CDN (based on the src value). This callback function is useful when you need to insert a telemetry initializer. It's passed one argument, which is a reference to the SDK instance that's being called for and is also called before the first initial page view. If the SDK has already been loaded and initialized, this callback is still called. NOTE: During the processing of the sdk.queue array, this callback is called. You CANNOT add any more items to the queue because they're ignored and dropped. (Added as part of JavaScript (Web) SDK Loader Script version 5--the sv:"5" value within the script).
crbooleanOptionalIf the SDK fails to load and the endpoint value defined for src is the public CDN location, this configuration option attempts to immediately load the SDK from one of the following backup CDN endpoints:
  • js.monitor.azure.com
  • js.cdn.applicationinsights.io
  • js.cdn.monitor.azure.com
  • js0.cdn.applicationinsights.io
  • js0.cdn.monitor.azure.com
  • js2.cdn.applicationinsights.io
  • js2.cdn.monitor.azure.com
  • az416426.vo.msecnd.net
NOTE: az416426.vo.msecnd.net is partially supported, so it's not recommended.

If the SDK successfully loads from a backup CDN endpoint, it loads from the first available one, which is determined when the server performs a successful load check. If the SDK fails to load from any of the backup CDN endpoints, the SDK Failure error message appears.

When not defined, the default value is true. If you don’t want to load the SDK from the backup CDN endpoints, set this configuration option to false.

If you’re loading the SDK from your own privately hosted CDN endpoint, this configuration option isn't applicable.

Paste the connection string in your environment

To paste the connection string in your environment, follow these steps:

  1. Navigate to the Overview pane of your Application Insights resource.

  2. Locate the Connection String.

  3. Select the Copy to clipboard icon to copy the connection string to the clipboard.

    Screenshot that shows Application Insights overview and connection string.

  4. Replace the placeholder "YOUR_CONNECTION_STRING" in the JavaScript code with your connection string copied to the clipboard.

    The connectionString format must follow "InstrumentationKey=xxxx;....". If the string provided doesn't meet this format, the SDK load process fails.

    The connection string isn't considered a security token or key. For more information, see Do new Azure regions require the use of connection strings?.

(Optional) Add SDK configuration

The optional SDK configuration is passed to the Application Insights JavaScript SDK during initialization.

To add SDK configuration, add each configuration option directly under connectionString. For example:

Screenshot of JavaScript code with SDK configuration options added and highlighted.

(Optional) Add advanced SDK configuration

If you want to use the extra features provided by plugins for specific frameworks and optionally enable the Click Analytics plug-in, see:

Confirm data is flowing

  1. Go to your Application Insights resource that you've enabled the SDK for.

  2. In the Application Insights resource menu on the left, under Investigate, select the Transaction search pane.

  3. Open the Event types dropdown menu and select Select all to clear the checkboxes in the menu.

  4. From the Event types dropdown menu, select:

    • Page View for Azure Monitor Application Insights Real User Monitoring
    • Custom Event for the Click Analytics Auto-Collection plug-in.

    It might take a few minutes for data to show up in the portal. If the only data you see showing up is a load failure exception, see Troubleshoot SDK load failure for JavaScript web apps.

    In some cases, if multiple instances of different versions of Application Insights are running on the same page, errors can occur during initialization. For these cases and the error message that appears, see Running multiple versions of the Application Insights JavaScript SDK in one session. If you've encountered one of these errors, try changing the namespace by using the name setting. For more information, see JavaScript (Web) SDK Loader Script configuration.

    Screenshot of the Application Insights Transaction search pane in the Azure portal with the Page View option selected. The page views are highlighted.

  5. If you want to query data to confirm data is flowing:

    1. Select Logs in the left pane.

      When you select Logs, the Queries dialog opens, which contains sample queries relevant to your data.

    2. Select Run for the sample query you want to run.

    3. If needed, you can update the sample query or write a new query by using Kusto Query Language (KQL).