共用方式為


適用於 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. 如果您還沒有身分識別,請使用受控識別或服務主體來建立一個。

    • 我們建議使用受控識別:

      為 Azure 服務設定受控識別 (部分機器翻譯) (虛擬機器或 App Service)。

    • 不建議使用服務主體:

      如需如何建立可存取資源的 Microsoft Entra 應用程式和服務主體的詳細資訊,請參閱建立服務主體 (部分機器翻譯)。

  2. 將必要的角色型訪問控制 (RBAC) 角色指派給 Azure 身分識別、服務主體或 Azure 用戶帳戶。

    依照指派 Azure 角色中的步驟,將目標 Application Insights 資源設定為角色範圍,將監視計量發行者角色新增至預期的身分識別、服務主體或 Azure 用戶帳戶。

    注意

    雖然「監視計量發行者」角色的名稱中只註明「計量」,其會將所有遙測發佈至 Application Insights 資源。

  3. 請按照下列語言遵循相關設定指導方針。

注意

Application Insights .NET SDK 從 2.18-Beta3 版 (英文) 開始包括對 Microsoft Entra ID 的支援。

Application Insights .NET SDK 支援 Azure 身分識別所提供的認證類別。

  • 我們建議針對本機開發使用 DefaultAzureCredential
  • 請確定您已使用預期的 Azure 用戶帳戶在 Visual Studio 上驗證。 如需詳細資訊,請參閱 透過Visual Studio進行驗證。
  • 建議針對系統指派和使用者指派的受控識別使用 ManagedIdentityCredential
    • 若為系統指派,請使用不含參數的預設建構函式。
    • 針對使用者指派,請將用戶端識別碼提供給建構函式。

下列範例示範如何使用 .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 監視器 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 租用戶識別碼。
  • 您的 App Insights 應用程式識別碼 - 如果您目前使用 API 金鑰,則其應用程式識別子相同。
  • 應用程式的 Microsoft Entra 用戶端識別碼。
  • 應用程式的 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 監視器 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 應用程式的應用程式識別碼。 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

成功的要求會產生重新導向至您的重新導向 URI,並在 URL 中包含權杖:

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

當此access_token傳遞至 Application Insights API 以授權要求時,此access_token做為 Authorization: Bearer 標頭值。

停用本機驗證

啟用 Microsoft Entra 驗證之後,您可以選擇停用本機驗證。 此設定允許您內嵌由 Microsoft Entra ID 獨佔驗證的遙測資料,而且會影響資料存取 (例如透過 API 金鑰)。

您可以使用 Azure 入口網站或 Azure 原則,或以程式設計方式停用本機驗證。

Azure 入口網站

  1. 從 Application Insights 資源中,選取左側功能表中 [設定] 底下的 [屬性]。 若已啟用本機驗證,請選取 [已啟用 (按一下以變更)]

    顯示 [設定] 區段下 [屬性] 和 [啟用] [選取變更] 本機驗證按鈕的螢幕快照。

  2. 選取 [停用] 並套用變更。

    顯示本機驗證的螢幕快照,其中包含 [已啟用/停用] 按鈕。

  3. 停用資源上的本機驗證之後,您會在 [概觀] 窗格中看到對應的資訊。

    顯示 [概觀] 索引標籤的螢幕快照,其中包含 [已停用] [選取變更] 本機驗證按鈕。

Azure 原則

在沒有將 DisableLocalAuth 設定為 true 的情況下,此屬性的 Azure 原則會拒絕使用者建立新的 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 驗證用於所有存取。

下列範例顯示可用來建立已停用 LocalAuth 的工作區型 Application Insights 資源的 Azure Resource Manager 範本。

{
    "$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
由 21Vianet Cloud 營運的 Microsoft Azure https://monitor.azure.cn
Azure 美國政府雲端 https://monitor.azure.us

如果您使用主權雲端,您也可以在連接字串中找到對象資訊。 連接字串會遵循此結構:

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

audience 參數 AADAudience 可能會根據您的特定環境而有所不同。

疑難排解

本節提供不同的疑難排解情節和步驟,讓您可以在提出支援票證之前先解決問題。

擷取 HTTP 錯誤

無論何種 SDK 語言,內嵌服務都會傳回特定錯誤。 您可以使用 Fiddler 之類的工具來收集網路流量。 您應該篩選連接字串中所設定之內嵌端點的流量。

不支援 HTTP/1.1 400 驗證

此錯誤顯示資源是針對僅限 Microsoft Entra 設定的。 您必須正確設定 SDK,因為它傳送到錯誤的 API。

注意

"v2/track" 不支援 Microsoft Entra ID。 正確設定 SDK 時,會傳送遙測資料至 "v2/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:

下一步