你当前正在访问 Microsoft Azure Global Edition 技术文档网站。 如果需要访问由世纪互联运营的 Microsoft Azure 中国技术文档网站,请访问 https://docs.azure.cn

Application Insights 的 Microsoft Entra 身份验证

Application Insights 现在支持 Microsoft Entra 身份验证。 通过使用 Microsoft Entra ID,可以确保在 Application Insights 资源中仅引入经过身份验证的遥测数据。

使用各种身份验证系统可能既麻烦又有风险,因为很难大规模管理凭据。 你现在可以选择退出本地身份验证,以确保只在资源中引入使用托管标识Microsoft Entra ID 专门进行身份验证的遥测数据。 此功能是增强用于执行关键操作(警报自动缩放)和业务决策的遥测的安全性和可靠性的一个步骤。

先决条件

若要启用经由 Microsoft Entra 身份验证的引入,需要执行以下初步步骤。 你需要:

不支持的方案

不支持将以下软件开发工具包 (SDK) 和功能用于 Microsoft Entra 身份验证引入:

配置和启用基于 Microsoft Entra ID 的身份验证

  1. 如果你还没有标识,请使用托管标识或服务主体创建一个。

  2. 将所需的基于角色的访问控制 (RBAC) 角色分配给 Azure 标识、服务主体或 Azure 用户帐户。

    按照分配 Azure 角色中的步骤,通过将目标 Application Insights 资源设置为角色作用域来向预期标识、服务主体或 Azure 用户帐户添加“监视指标发布者”角色。

    注意

    尽管“监视指标发布者”角色名字里有“指标”,但它会将所有遥测数据发布到 Application Insights 资源。

  3. 遵循配置指南,并按照后面的语言进行操作。

注意

版本 2.18-Beta3 开始,包含对 Application Insights .NET SDK 中 Microsoft Entra ID 的支持。

Application Insights .NET SDK 支持 Azure 标识提供的凭据类。

  • 建议使用 DefaultAzureCredential 进行本地开发。
  • 确保已使用预期的 Azure 用户帐户在 Visual Studio 上进行了身份验证。 有关详细信息,请参阅通过 Visual Studio 进行身份验证
  • 建议使用 ManagedIdentityCredential 处理系统分配和用户分配的托管标识。
    • 对于系统分配的托管标识,使用不带参数的默认构造函数。
    • 对于用户分配的托管标识,请向构造函数提供客户端 ID。

以下示例演示如何使用 .NET 手动创建和配置 TelemetryConfiguration

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

以下示例演示如何使用 .NET Core 配置 TelemetryConfiguration

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

使用 Microsoft Entra 身份验证查询 Application Insights

可以使用 Azure Monitor Application Insights 终结点 https://api.applicationinsights.io 提交查询请求。 若要访问终结点,必须通过 Microsoft Entra ID 进行身份验证。

设置身份验证

若要访问 API,请向 Microsoft Entra ID 注册客户端应用并请求令牌。

  1. 在 Microsoft Entra ID 中注册应用

  2. 在应用的概述页面中,选择“API 权限”。

  3. 选择“添加权限”。

  4. 在“我的组织使用的 API”选项卡上,搜索“Application Insights”,然后从列表中选择“Application Insights API”。

  5. 选择“委托的权限”。

  6. 选中“Data.Read”复选框。

  7. 选择“添加权限”。

现在,应用已注册完成并有权使用 API,请授予你的应用对 Application Insights 资源的访问权限。

  1. Application Insights 资源概述页中,选择“访问控制 (IAM)”。

  2. 选择“添加角色分配”。

  3. 选择“读取者”角色,然后选择“成员”。

  4. 在“成员”选项卡上,选择“选择成员”。

  5. 在“选择”框中,输入应用的名称。

  6. 选择应用,然后选择“选择”。

  7. 选择“查看 + 分配”。

  8. 在完成 Active Directory 设置和权限事项后,请请求授权令牌。

注意

在此示例中,我们应用了“读取者”角色。 此角色是许多内置角色之一,可能包含超过所需的权限。 可以创建更精细的角色和权限。

请求获取授权令牌

在开始之前,请确保你拥有成功进行请求所需的所有值。 所有请求都需要:

  • Microsoft Entra 租户 ID。
  • App Insights 应用 ID - 如果当前使用的是 API 密钥,则使用相同的应用 ID。
  • 应用的 Microsoft Entra 客户端 ID。
  • 应用的 Microsoft Entra 客户端密码。

Application Insights API 通过三种不同的 Microsoft Entra ID OAuth2 流支持 Microsoft Entra 身份验证:

  • 客户端凭据
  • 授权代码
  • 隐式

客户端凭据流

在客户端凭据流中,令牌用于 Application Insights 终结点。 使用上述在 Microsoft Entra ID 中注册应用的步骤中为应用提供的凭据,发出单个请求来接收令牌。

使用 https://api.applicationinsights.io 终结点。

客户端凭据令牌 URL(POST 请求)
    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>

成功的请求在响应中接收访问令牌:

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

在对 Application Insights 终结点的请求中使用令牌:

    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"
    }

示例响应:

  "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"
        ]
      ]
    }
  ]
}

授权代码流

支持的主要 OAuth2 流是通过授权代码实现的。 此方法需要两个 HTTP 请求来获取用于调用 Azure Monitor Application Insights API 的令牌。 有两个 URL,每个请求对应一个终结点。 后续章节将介绍其格式。

授权代码 URL(GET 请求)
    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

向授权 URL 发出请求时,client_id 是 Microsoft Entra 应用提供的应用程序 ID(从应用的属性菜单中复制)。 redirect_uri 是来自同一 Microsoft Entra 应用的主页/登录 URL。 请求成功时,此终结点会将你重定向到你在注册时提供的登录页,并将授权代码追加到 URL。 请参阅以下示例:

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

此时,你将获取授权代码,该代码现在用于请求访问令牌。

授权代码令牌 URL(POST 请求)
    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>

所有值都与以前相同,只是增加了一些值。 该授权代码与在成功重定向后在上一个请求中收到的代码相同。 该代码与从 Microsoft Entra 应用获取的密钥结合在一起。 如果未保存该密钥,可将其删除,并从 Microsoft Entra 应用菜单的“密钥”选项卡中创建一个新密钥。 响应是包含具有以下架构的令牌的 JSON 字符串。 为令牌值指明了类型。

响应示例:

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

此响应的访问令牌部分是在 Authorization: Bearer 标头中提供给 Application Insights API 的内容。 将来如果令牌过时,还可以使用刷新令牌来获取新的 access_token 和 refresh_token。 对于此请求,格式和终结点为:

    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>

响应示例:

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

隐式代码流

Application Insights API 还支持 OAuth2 隐式流。 对于此流,只需要单个请求,但无法获取刷新令牌。

隐式代码授权 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

成功的请求将使用 URL 中的令牌生成到你的重定向 URI 的重定向:

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

此 access_token 将在传递给 Application Insights API 以授权请求时充当 Authorization: Bearer 标头值。

“禁用本地身份验证”

启用 Microsoft Entra 身份验证后,可以选择禁用本地身份验证。 使用此配置可以引入由 Microsoft Entra ID 专门验证的遥测数据,这将影响数据访问(例如通过 API 密钥访问数据)。

可以使用 Azure 门户、Azure Policy 或以编程方式禁用本地身份验证。

Azure 门户

  1. 在 Application Insights 资源中,选择左侧菜单中“配置”下的“属性”。 如果已启用本地身份验证,请选择“已启用(单击更改)”。

    屏幕截图显示了“配置”部分下的“属性”和“已启用(单击更改)”本地身份验证按钮。

  2. 选择“已禁用”并应用更改。

    显示本地身份验证的屏幕截图,其中有“已启用”/“已禁用”按钮。

  3. 在资源上禁用本地身份验证后,“概述”窗格中将显示相应的信息

    屏幕截图显示了“概述”选项卡,其中突出显示了“已禁用(单击更改)”本地身份验证按钮。

Azure Policy

DisableLocalAuth 的 Azure Policy 拒绝用户在未将此属性设置为 true 的情况下创建新的 Application Insights 资源。 策略名称为 Application Insights components should block non-AAD auth ingestion

若要将此策略定义应用到订阅,请创建新的策略分配并分配该策略

以下示例显示了策略模板定义:

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

编程启用

属性 DisableLocalAuth 用于禁用你的 Application Insights 资源上的任何本地身份验证。 设置为 true 时,此属性强制所有访问都必须使用 Microsoft Entra 身份验证。

下面的示例展示了 Azure 资源管理器模板,可用于创建禁用 LocalAuth 的基于工作区的 Application Insights 资源。

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

令牌受众

在开发自定义客户端以从 Microsoft Entra ID 获取访问令牌以将遥测数据提交到 Application Insights 时,请参阅下表以确定适合特定主机环境的受众字符串。

Azure 云版本 令牌受众值
Azure 公有云 https://monitor.azure.com
由世纪互联运营的 Microsoft Azure 云 https://monitor.azure.cn
Azure 美国政府云 https://monitor.azure.us

如果使用主权云,还可以在连接字符串中找到受众信息。 连接字符串遵循以下结构:

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

受众参数 AADAudience 可能因具体环境而异。

故障排除

本部分提供了不同的故障排除场景和步骤,你可以在提交支持工单之前采取这些步骤来解决问题。

引入 HTTP 错误

引入服务会返回具体错误,而不考虑 SDK 语言。 可以使用 Fiddler 之类的工具收集网络流量。 你应该要筛选发往连接字符串中设置的引入终结点的流量。

不支持 HTTP/1.1 400 身份验证

此错误显示资源设置为仅限 Microsoft Entra 使用。 需要正确配置 SDK,因为它正在发送到错误的 API。

注意

“v2/track”不支持 Microsoft Entra ID。 正确配置 SDK 后,遥测数据将发送到“v2.1/track”。

接下来,你应该查看 SDK 配置。

需要 HTTP/1.1 401 授权

此错误表示 SDK 已正确配置,但无法获取有效的令牌。 此错误可能表示 Microsoft Entra ID 存在问题。

接下来,需要识别 SDK 日志中的异常或来自 Azure 标识的网络错误。

HTTP/1.1 403 未授权

此错误表示 SDK 使用的凭据没有 Application Insights 资源或订阅的权限。

首先,检查 Application Insights 资源的访问控制。 必须使用具有“监视指标发布者”角色的凭据配置 SDK。

特定于语言的疑难解答

事件源

Application Insights .NET SDK 使用事件源发出错误日志。 若要详细了解如何收集事件源日志,请参阅疑难解答:无数据 - 使用 PerfView 收集日志

如果 SDK 未能获取令牌,则异常消息将记录为 Failed to get AAD Token. Error message:

后续步骤