共用方式為


適用於 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. 請按照下列語言遵循相關設定指導方針。

附註

  • Application Insights .NET SDK 從 2.18-Beta3 版 (英文) 開始包括對 Microsoft Entra ID 的支援。
  • 我們支援 Azure 身分識別所提供的認證類別。
  • 我們建議針對本機開發使用 DefaultAzureCredential
  • 在 Visual Studio 上使用預期的 Azure 使用者帳戶進行驗證。 如需詳細資訊,請參閱透過 Visual Studio 進行驗證
  • 建議針對系統指派和使用者指派的受控識別使用 ManagedIdentityCredential
    • 若為系統指派,請使用不含參數的預設建構函式。
    • 針對使用者指派,請將用戶端識別碼提供給建構函式。
  1. 安裝最新的 Azure.Identity 套件:

    dotnet add package Azure.Identity
    
  2. 提供所需的認證類別:

    // 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();
    

環境變數設定

使用 APPLICATIONINSIGHTS_AUTHENTICATION_STRING 環境變數,以便讓 Application Insights 驗證至 Microsoft Entra ID 並在使用 Azure App Services 自動儀表化 時傳送遙測。

  • 針對系統指派的身分識別:
應用程式設定
APPLICATIONINSIGHTS_AUTHENTICATION_STRING Authorization=AAD
  • 針對使用者指派的身分識別:
應用程式設定
APPLICATIONINSIGHTS_AUTHENTICATION_STRING Authorization=AAD;ClientId={Client id of the User-Assigned Identity}

Classic API

下列範例示範如何使用 .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 應用程式的 homepage/login 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 以授權要求時,會作為 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-Azure Active Directory based ingestion

若要將此原則定義套用至訂用帳戶,請建立新的原則指派並指派原則

下列範例顯示原則範本定義:

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

程式設計啟用

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}

視您的特定環境而定,對象參數 AADAudience 可能會有所不同。

疑難排解

如需疑難排解指引,請參閱 針對 Microsoft Entra 驗證問題進行疑難排解

下一步