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:
- Be in the public cloud.
- Be familiar with:
- Granting access using Azure built-in roles requires having an Owner role to the resource group.
- Understand the unsupported scenarios.
Unsupported scenarios
The following Software Development Kits (SDKs) and features are unsupported for use with Microsoft Entra authenticated ingestion:
- Application Insights Java 2.x SDK.
Microsoft Entra authentication is only available for Application Insights Java Agent greater than or equal to 3.2.0. - ApplicationInsights JavaScript web SDK.
- Application Insights OpenCensus Python SDK with Python version 3.4 and 3.5.
- AutoInstrumentation for Python on Azure App Service
- Application Insights Profiler for .NET.
Configure and enable Microsoft Entra ID-based authentication
If you don't already have an identity, create one by using either a managed identity or a service principal.
We recommend using a managed identity:
Set up a managed identity for your Azure service (Virtual Machines or App Service).
We don't recommend using a service principal:
For more information on how to create a Microsoft Entra application and service principal that can access resources, see Create a service principal.
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.
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. - 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.
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);
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/"
});
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} |
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.
On the app's overview page, select API permissions.
Select Add a permission.
On the APIs my organization uses tab, search for Application Insights and select Application Insights API from the list.
Select Delegated permissions.
Select the Data.Read checkbox.
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.
From your Application Insights resource overview page, select Access control (IAM).
Select Add role assignment.
Select the Reader role and then select Members.
On the Members tab, choose Select members.
Enter the name of your app in the Select box.
Select your app and choose Select.
Select Review + assign.
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
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.
Select Disabled and apply changes.
After disabling local authentication on your resource, you'll see the corresponding information in the Overview pane.
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 will be 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
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:
.