Skip to content

Latest commit

 

History

History
1152 lines (891 loc) · 47.2 KB

azure-ad-authentication.md

File metadata and controls

1152 lines (891 loc) · 47.2 KB
title description ms.topic ms.date ms.devlang ms.reviewer
Microsoft Entra authentication for Application Insights
Learn how to enable Microsoft Entra authentication to ensure that only authenticated telemetry is ingested in your Application Insights resources.
conceptual
01/31/2025
csharp
rijolly

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. Create an identity using a managed identity or a service principal if you don't already have one.

  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 publishes 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.
  • We support the credential classes provided by Azure Identity.
  • We recommend DefaultAzureCredential for local development.
  • Authenticate 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.
  1. Install the latest Azure.Identity package:

    dotnet add package Azure.Identity
    
  2. Provide the desired credential class:

    // Create a new ASP.NET Core web application builder.    
    var builder = WebApplication.CreateBuilder(args);
    
    // Add the OpenTelemetry telemetry service to the application.
    // This service will collect and send telemetry data to Azure Monitor.
    builder.Services.AddOpenTelemetry().UseAzureMonitor(options => {
        // Set the Azure Monitor credential to the DefaultAzureCredential.
        // This credential will use the Azure identity of the current user or
        // the service principal that the application is running as to authenticate
        // to Azure Monitor.
        options.Credential = new DefaultAzureCredential();
    });
    
    // Build the ASP.NET Core web application.
    var app = builder.Build();
    
    // Start the ASP.NET Core web application.
    app.Run();

Environment variable configuration

Use the APPLICATIONINSIGHTS_AUTHENTICATION_STRING environment variable to let Application Insights authenticate to Microsoft Entra ID and send telemetry when using Azure App Services autoinstrumentation.

  • For system-assigned identity:
App setting Value
APPLICATIONINSIGHTS_AUTHENTICATION_STRING Authorization=AAD
  • For user-assigned identity:
App setting Value
APPLICATIONINSIGHTS_AUTHENTICATION_STRING Authorization=AAD;ClientId={Client id of the User-Assigned Identity}

Classic API

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

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/"
});

Note

  • Support for Microsoft Entra ID in the Application Insights .NET SDK is included starting with version 2.18-Beta3.
  • We support the credential classes provided by Azure Identity.
  • We recommend DefaultAzureCredential for local development.
  • Authenticate 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.
  1. Install the latest Azure.Identity package:

    dotnet add package Azure.Identity
    
  2. Provide the desired credential class:

    // Create a DefaultAzureCredential.
    var credential = new DefaultAzureCredential();
    
    // Create a new OpenTelemetry tracer provider and set the credential.
    // It is important to keep the TracerProvider instance active throughout the process lifetime.
    var tracerProvider = Sdk.CreateTracerProviderBuilder()
        .AddAzureMonitorTraceExporter(options =>
        {
            options.Credential = credential;
        })
        .Build();
    
    // Create a new OpenTelemetry meter provider and set the credential.
    // It is important to keep the MetricsProvider instance active throughout the process lifetime.
    var metricsProvider = Sdk.CreateMeterProviderBuilder()
        .AddAzureMonitorMetricExporter(options =>
        {
            options.Credential = credential;
        })
        .Build();
    
    // Create a new logger factory and add the OpenTelemetry logger provider with the credential.
    // It is important to keep the LoggerFactory instance active throughout the process lifetime.
    var loggerFactory = LoggerFactory.Create(builder =>
    {
        builder.AddOpenTelemetry(logging =>
        {
            logging.AddAzureMonitorLogExporter(options =>
            {
                options.Credential = credential;
            });
        });
    });

Environment variable configuration

Use the APPLICATIONINSIGHTS_AUTHENTICATION_STRING environment variable to let Application Insights authenticate to Microsoft Entra ID and send telemetry when using Azure App Services autoinstrumentation.

  • For system-assigned identity:
App setting Value
APPLICATIONINSIGHTS_AUTHENTICATION_STRING Authorization=AAD
  • For user-assigned identity:
App setting Value
APPLICATIONINSIGHTS_AUTHENTICATION_STRING Authorization=AAD;ClientId={Client id of the User-Assigned Identity}

Classic API

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

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

Note

  • Support for Microsoft Entra ID in the Application Insights Java agent is included starting with Java 3.2.0-BETA.
  • We support the credential classes provided by Azure Identity.
  1. Configure your application with the Java agent.

    [!IMPORTANT] Use the full connection string, which includes IngestionEndpoint, when you configure your app with the Java agent. For example, use InstrumentationKey=XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX;IngestionEndpoint=https://XXXX.applicationinsights.azure.com/.

  2. Add the JSON configuration to the ApplicationInsights.json configuration file depending on the authentication you're using. We recommend using managed identities.

Environment variable configuration

The APPLICATIONINSIGHTS_AUTHENTICATION_STRING environment variable allows Application Insights to authenticate with Microsoft Entra ID and send telemetry. Configure it based on the type of identity you're using:

  • System-assigned identity
    Set the APPLICATIONINSIGHTS_AUTHENTICATION_STRING environment variable to:

    Authorization=AAD
    
  • User-assigned identity
    Set the APPLICATIONINSIGHTS_AUTHENTICATION_STRING environment variable to:

    Authorization=AAD;ClientId={Client id of the User-Assigned Identity}
    

    Replace {Client id of the User-Assigned Identity} with the actual client ID of your user-assigned identity.

Set the APPLICATIONINSIGHTS_AUTHENTICATION_STRING environment variable using this string.

In Unix/Linux:

export APPLICATIONINSIGHTS_AUTHENTICATION_STRING="Authorization=AAD"

In Windows:

set APPLICATIONINSIGHTS_AUTHENTICATION_STRING="Authorization=AAD"

After setting it, restart your application. It now sends telemetry to Application Insights using Microsoft Entra authentication.

Manual configuration

Note

System-assigned managed identity

The following example shows how to configure the Java agent to use system-assigned managed identity for authentication with Microsoft Entra ID.

{ 
  "connectionString": "App Insights Connection String with IngestionEndpoint", 
  "authentication": { 
    "enabled": true, 
    "type": "SAMI" 
  } 
} 
User-assigned managed identity

The following example shows how to configure the Java agent to use user-assigned managed identity for authentication with Microsoft Entra ID.

{ 
  "connectionString": "App Insights Connection String with IngestionEndpoint", 
  "authentication": { 
    "enabled": true, 
    "type": "UAMI", 
    "clientId":"<USER-ASSIGNED MANAGED IDENTITY CLIENT ID>" 
  } 
} 

:::image type="content" source="media/azure-ad-authentication/user-assigned-managed-identity.png" alt-text="Screenshot that shows user-assigned managed identity." lightbox="media/azure-ad-authentication/user-assigned-managed-identity.png":::

Microsoft Entra ID authentication isn't available for GraalVM Native applications.

Note

  • Support for Microsoft Entra ID in the Application Insights Node.JS is included starting with version 2.1.0-beta.1.
  • We support the credential classes provided by Azure Identity.
  • We recommend DefaultAzureCredential for local development.
  • 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.
  • We recommend ClientSecretCredential for service principals.
    • Provide the tenant ID, client ID, and client secret to the constructor.

Environment variable configuration

Use the APPLICATIONINSIGHTS_AUTHENTICATION_STRING environment variable to let Application Insights authenticate to Microsoft Entra ID and send telemetry when using Azure App Services autoinstrumentation.

  • For system-assigned identity:
App setting Value
APPLICATIONINSIGHTS_AUTHENTICATION_STRING Authorization=AAD
  • For user-assigned identity:
App setting Value
APPLICATIONINSIGHTS_AUTHENTICATION_STRING Authorization=AAD;ClientId={Client id of the User-Assigned Identity}

Manual configuration

The following sample applies when using @azure/monitor-opentelemetry:

// Import the useAzureMonitor function, the AzureMonitorOpenTelemetryOptions class, and the ManagedIdentityCredential class from the @azure/monitor-opentelemetry and @azure/identity packages, respectively.
const { useAzureMonitor, AzureMonitorOpenTelemetryOptions } = require("@azure/monitor-opentelemetry");
const { ManagedIdentityCredential } = require("@azure/identity");

// Create a new ManagedIdentityCredential object.
const credential = new ManagedIdentityCredential();

// Create a new AzureMonitorOpenTelemetryOptions object and set the credential property to the credential object.
const options: AzureMonitorOpenTelemetryOptions = {
    azureMonitorExporterOptions: {
        connectionString:
            process.env["APPLICATIONINSIGHTS_CONNECTION_STRING"] || "<your connection string>",
        credential: credential
    }
};

// Enable Azure Monitor integration using the useAzureMonitor function and the AzureMonitorOpenTelemetryOptions object.
useAzureMonitor(options);

The following sample applies when using applicationinsights npm package.

// Import the applicationinsights module and the DefaultAzureCredential class from the @azure/identity package.
const appInsights = require("applicationinsights");
const { DefaultAzureCredential } = require("@azure/identity");

// Create a new DefaultAzureCredential object to authenticate with Azure Active Directory.
const credential = new DefaultAzureCredential();

// Set up Application Insights with an instrumentation key and ingestion endpoint, then start the Application Insights client.
appInsights.setup("InstrumentationKey=00000000-0000-0000-0000-000000000000;IngestionEndpoint=https://xxxx.applicationinsights.azure.com/").start();

// Assign the DefaultAzureCredential object to the aadTokenCredential property of the default Application Insights client configuration for authentication.
appInsights.defaultClient.config.aadTokenCredential = credential;

Note

  • We recommend DefaultAzureCredential for local development.
  • 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.
  • We recommend ClientSecretCredential for service principals.
    • Provide the tenant ID, client ID, and client secret to the constructor.

If using ManagedIdentityCredential

# Import the `ManagedIdentityCredential` class from the `azure.identity` package.
from azure.identity import ManagedIdentityCredential
# Import the `configure_azure_monitor()` function from the `azure.monitor.opentelemetry` package.
from azure.monitor.opentelemetry import configure_azure_monitor
from opentelemetry import trace

# Configure the Distro to authenticate with Azure Monitor using a managed identity credential.
credential = ManagedIdentityCredential(client_id="<client_id>")
configure_azure_monitor(
    connection_string="your-connection-string",
    credential=credential,
)

tracer = trace.get_tracer(__name__)

with tracer.start_as_current_span("hello with aad managed identity"):
    print("Hello, World!")

If using ClientSecretCredential

# Import the `ClientSecretCredential` class from the `azure.identity` package.
from azure.identity import ClientSecretCredential
# Import the `configure_azure_monitor()` function from the `azure.monitor.opentelemetry` package.
from azure.monitor.opentelemetry import configure_azure_monitor
from opentelemetry import trace

# Configure the Distro to authenticate with Azure Monitor using a client secret credential.
credential = ClientSecretCredential(
    tenant_id="<tenant_id",
    client_id="<client_id>",
    client_secret="<client_secret>",
)
configure_azure_monitor(
    connection_string="your-connection-string",
    credential=credential,
)

with tracer.start_as_current_span("hello with aad client secret identity"):
    print("Hello, World!")

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.

Note

For this example, we applied the Reader role. This role is one of many built-in roles and might include more permissions than you require. More granular roles and permissions can be created.

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)
    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:

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

Use the token in requests to the Application Insights endpoint:

    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)
    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://<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)
    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:

    {
        "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:

    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:

    {
      "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
    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://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.

    :::image type="content" source="./media/azure-ad-authentication/enabled.png" alt-text="Screenshot that shows Properties under the Configure section and the Enabled (select to change) local authentication button.":::

  2. Select Disabled and apply changes.

    :::image type="content" source="./media/azure-ad-authentication/disable.png" alt-text="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.

    :::image type="content" source="./media/azure-ad-authentication/overview.png" alt-text="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-Azure Active Directory based 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:

{
    "properties": {
        "displayName": "Application Insights components should block non-Azure Active Directory based 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.

{
    "$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')]"
            }
    }
 ]
}

Token audience

When developing a custom client to obtain an access token from Microsoft Entra ID for submitting telemetry to Application Insights, refer to the following table to determine the appropriate audience string for your particular host environment.

Azure cloud version Token audience value
Azure public cloud https://monitor.azure.com
Microsoft Azure operated by 21Vianet cloud https://monitor.azure.cn
Azure US Government cloud https://monitor.azure.us

If you're using sovereign clouds, you can find the audience information in the connection string as well. The connection string follows this structure:

InstrumentationKey={profile.InstrumentationKey};IngestionEndpoint={ingestionEndpoint};LiveEndpoint={liveDiagnosticsEndpoint};AADAudience={aadAudience}

The audience parameter, AADAudience, can vary depending on your specific environment.

Troubleshooting

This section provides distinct troubleshooting scenarios and steps that you can take to resolve an issue before you raise a support ticket.

Ingestion HTTP errors

The ingestion service returns specific errors, regardless of the SDK language. Network traffic can be collected by using a tool such as Fiddler. You should filter traffic to the ingestion endpoint set in the connection string.

HTTP/1.1 400 Authentication not supported

This error shows the resource is set for Microsoft Entra-only. You need to correctly configure the SDK because it's sending to the wrong API.

Note

"v2/track" doesn't support Microsoft Entra ID. When the SDK is correctly configured, telemetry is sent to v2.1/track.

Next, you should review the SDK configuration.

HTTP/1.1 401 Authorization required

This error indicates that the SDK is correctly configured but it's unable to acquire a valid token. This error might indicate an issue with Microsoft Entra ID.

Next, you should identify exceptions in the SDK logs or network errors from Azure Identity.

HTTP/1.1 403 Unauthorized

This error means the SDK uses credentials without permission for the Application Insights resource or subscription.

First, check the Application Insights resource's access control. You must configure the SDK with credentials that have the Monitoring Metrics Publisher role.

Language-specific troubleshooting

The Application Insights .NET SDK emits error logs by using the event source. To learn more about collecting event source logs, see Troubleshooting no data - collect logs with PerfView.

If the SDK fails to get a token, the exception message is logged as Failed to get AAD Token. Error message:.

Event source

The Application Insights .NET SDK emits error logs by using the event source. To learn more about collecting event source logs, see Troubleshooting no data - collect logs with PerfView.

If the SDK fails to get a token, the exception message is logged as Failed to get AAD Token. Error message:.

HTTP traffic

You can inspect network traffic by using a tool like Fiddler. To enable the traffic to tunnel through Fiddler, either add the following proxy settings in the configuration file:

"proxy": {
"host": "localhost",
"port": 8888
}

Or add the following Java Virtual Machine (JVM) args while running your application: -Djava.net.useSystemProxies=true -Dhttps.proxyHost=localhost -Dhttps.proxyPort=8888

If Microsoft Entra ID is enabled in the agent, outbound traffic includes the HTTP header Authorization.

401 Unauthorized

If you see the message, WARN c.m.a.TelemetryChannel - Failed to send telemetry with status code: 401, please check your credentials in the log, it means the agent couldn't send telemetry. You likely didn't enable Microsoft Entra authentication on the agent, while your Application Insights resource has DisableLocalAuth: true. Ensure you pass a valid credential with access permission to your Application Insights resource.

If you're using Fiddler, you might see the response header HTTP/1.1 401 Unauthorized - please provide the valid authorization token.

CredentialUnavailableException

If you see the exception, com.azure.identity.CredentialUnavailableException: ManagedIdentityCredential authentication unavailable. Connection to IMDS endpoint cannot be established in the log file, it means the agent failed to acquire the access token. The likely cause is an invalid client ID in your User-Assigned Managed Identity configuration.

Failed to send telemetry

If you see the message, WARN c.m.a.TelemetryChannel - Failed to send telemetry with status code: 403, please check your credentials in the log, it means the agent couldn't send telemetry. The likely reason is that the credentials used don't allow telemetry ingestion.

Using Fiddler, you might notice the response HTTP/1.1 403 Forbidden - provided credentials do not grant the access to ingest the telemetry into the component.

The issue could be due to:

  • Creating the resource with a system-assigned managed identity or associating a user-assigned identity without adding the Monitoring Metrics Publisher role to it.
  • Using the correct credentials for access tokens but linking them to the wrong Application Insights resource. Ensure your resource (virtual machine or app service) or user-assigned identity has Monitoring Metrics Publisher roles in your Application Insights resource.

Invalid Client ID

If the exception, com.microsoft.aad.msal4j.MsalServiceException: Application with identifier <CLIENT_ID> was not found in the directory in the log, it means the agent failed to get the access token. This exception likely happens because the client ID in your client secret configuration is invalid or incorrect.

This issue occurs if the administrator doesn't install the application or no tenant user consents to it. It also happens if you send your authentication request to the wrong tenant.

Microsoft Entra ID authentication isn't available for GraalVM Native applications.

Turn on internal logs by using the following setup. After you enable them, the console shows error logs, including any error related to Microsoft Entra integration. Examples include failing to generate the token with the wrong credentials or errors when the ingestion endpoint fails to authenticate using the provided credentials.

let appInsights = require("applicationinsights");
appInsights.setup("InstrumentationKey=00000000-0000-0000-0000-000000000000;IngestionEndpoint=https://xxxx.applicationinsights.azure.com/").setInternalLogging(true, true);

Error starts with "credential error" (with no status code)

Something is incorrect about the credential you're using and the client isn't able to obtain a token for authorization. It's because the required data is lacking for the state. An example would be passing in a system ManagedIdentityCredential but the resource isn't configured to use system-managed identity.

Error starts with "authentication error" (with no status code)

The client failed to authenticate with the given credential. This error usually occurs when the credential used doesn't have the correct role assignments.

I'm getting a status code 400 in my error logs

You're probably missing a credential or your credential is set to None, but your Application Insights resource is configured with DisableLocalAuth: true. Make sure you're passing in a valid credential and that it has permission to access your Application Insights resource.

I'm getting a status code 403 in my error logs

This error usually occurs when the provided credentials don't grant access to ingest telemetry for the Application Insights resource. Make sure your Application Insights resource has the correct role assignments.


Next steps