Share via


撰寫用戶端應用程式驗證程式碼

設定 Azure Digital Twins 執行個體和驗證之後,您可以建立用戶端應用程式以用來與執行個體互動。 設定入門用戶端專案之後,您必須在該用戶端應用程式中撰寫驗證程式碼,以向 Azure Digital Twins 執行個體進行驗證。

Azure Digital Twins 會使用根據 OAUTH 2.0 的 Microsoft Entra 安全性權杖進行驗證。 若要使用您的 SDK 進行驗證,您必須取得對 Azure Digital Twins 具有正確權限的持有人權杖,並隨著 API 呼叫一起傳遞。

本文說明如何使用 Azure.Identity 用戶端程式庫來取得認證。 雖然本文顯示 C# 程式碼範例,但就像您為 .NET (C#) SDK 撰寫程式碼一樣,您使用的 Azure.Identity 版本不需要考慮您使用何種 SDK (如需適用於 Azure Digital Twins 的 SDK 的詳細資訊,請參閱 Azure Digital Twins API 和 SDK

必要條件

首先,完成設定執行個體和驗證中的設定步驟。 此設定可確保您有 Azure Digital Twins 執行個體,而且您的使用者具有存取權限。 設定之後,就可以開始撰寫用戶端應用程式的程式碼。

若要繼續,您需要有用戶端應用程式專案來撰寫程式碼。 如果您尚未設定用戶端應用程式專案,請使用您選擇的語言來建立基本專案,以用於本教學課程。

使用 Azure.Identity 程式庫進行驗證

Azure.Identity 是一種用戶端程式庫,提供數種認證取得方法,可讓您用來取得持有人權杖,並使用您的 SDK 進行驗證。 雖然本文提供 C# 範例,但您可以檢視適用於數種語言的 Azure.Identity,包括...

Azure.Identity 中,三個常用的認證取得方法如下:

  • DefaultAzureCredential 為將部署至 Azure 的應用程式提供預設 TokenCredential 驗證流程,建議選擇用於本機開發。 另外可嘗試本文中建議的其他兩種方法;其中包裝 ManagedIdentityCredential,還可使用組態變數來存取 InteractiveBrowserCredential
  • ManagedIdentityCredential 在您需要受控識別 (MSI) 的情況下很有用,而且非常適合用於使用 Azure Functions 及部署至 Azure 服務。
  • InteractiveBrowserCredential 主要用於互動式應用程式,可用來建立已驗證的 SDK 用戶端。

本文的其餘部分說明如何搭配 .NET (C#) SDK 使用這些方法。

將 Azure.Identity 新增至 .NET 專案

若要設定 .NET 專案以使用 Azure.Identity 進行驗證,請完成下列步驟:

  1. 將 SDK 套件 Azure.DigitalTwins.CoreAzure.Identity 套件加入您的專案中。 視您選擇的工具而定,您可以使用 Visual Studio 套件管理員或 dotnet 命令列工具來添加套件。

  2. 將下列 using 陳述式新增至專案程式碼:

    using Azure.DigitalTwins.Core;
    using Azure.Identity;
    using System;
    

接下來,新增程式碼,以使用 Azure.Identity 的其中一種方法來取得認證。 下列各節詳細說明如何使用每一種方法。

DefaultAzureCredential 方法

DefaultAzureCredential 為將部署至 Azure 的應用程式提供預設 TokenCredential 驗證流程,建議選擇用於本機開發

若要使用預設的 Azure 認證,您需要 Azure Digital Twins 執行個體的 URL (依指示尋找)。

以下是將 DefaultAzureCredential 新增至專案的程式碼範例:

public class DefaultAzureCredentialSample
{
    // The URL of your instance, starting with the protocol (https://)
    private const string adtInstanceUrl = "https://<your-Azure-Digital-Twins-instance-URL>";

    internal void RunSample()
    {
        //...

        DigitalTwinsClient client;
        try
        {
            var credential = new DefaultAzureCredential();
            client = new DigitalTwinsClient(new Uri(adtInstanceUrl), credential);
        }
        catch (Exception e)
        {
            Console.WriteLine($"Authentication or client creation error: {e.Message}");
            Environment.Exit(0);
        }
    }
}

注意

目前有已知問題會影響 DefaultAzureCredential 包裝函式類別,這可能會導致在驗證時發生錯誤。 如果遇到此問題,您可以嘗試使用下列選擇性參數將 DefaultAzureCredential 具現化,以解決此問題:new DefaultAzureCredential(new DefaultAzureCredentialOptions { ExcludeSharedTokenCacheCredential = true });

如需關於此問題的詳細資訊,請參閱 Azure Digital Twins 已知問題

設定本機 Azure 認證

使用 DefaultAzureCredential,該範例會搜尋本機環境中的認證,例如在本機 Azure CLI 中或在 Visual Studio 或 Visual Studio Code 中的 Azure 登入。 因此,您應該透過下列其中一種機制本機登入 Azure,以設定該範例的認證。

如果您使用 Visual Studio 或 Visual Studio Code 來執行程式碼範例,請確定使用要用來存取 Azure Digital Twins 執行個體的相同 Azure 認證來登入該編輯器。 如果您使用本機 CLI 視窗,請執行 az login 命令來登入您的 Azure 帳戶。 之後,當您執行程式碼範例時,應該會自動驗證。

ManagedIdentityCredential 方法

ManagedIdentityCredential 方法在您需要受控識別 (MSI) 的情況下很有用,例如,使用 Azure Functions 進行驗證時。

這表示您可以在相同的專案中同時使用 ManagedIdentityCredentialDefaultAzureCredentialInteractiveBrowserCredential,以驗證專案的不同部分。

若要使用預設的 Azure 認證,您需要 Azure Digital Twins 執行個體的 URL (依指示尋找)。 您可能也需要應用程式註冊和註冊的應用程式 (用戶端) 識別碼

在 Azure 函式中,您可以如下使用受控識別認證:

public class ManagedIdentityCredentialSample
{
    // The URL of your instance, starting with the protocol (https://)
    private const string adtInstanceUrl = "https://<your-Azure-Digital-Twins-instance-URL>";

    internal void RunSample()
    {
        DigitalTwinsClient client;
        try
        {
            // To use the function app's system-assigned identity:
            ManagedIdentityCredential cred = new ManagedIdentityCredential();
            // To use a user-assigned identity for the function app:
            //ManagedIdentityCredential cred = new ManagedIdentityCredential("<uai-client-ID>");

            client = new DigitalTwinsClient(new Uri(adtInstanceUrl), cred);
        }
        catch (Exception e)
        {
            Console.WriteLine($"Authentication or client creation error: {e.Message}");
            Environment.Exit(0);
        }
    }
}

建立認證時,如果函式應用程式的系統指派身分識別具有認證,請將參數保留為空白,如上所示。 若要改為指定使用者指派的身分識別,請將使用者指派的身分識別用戶端識別碼傳遞至參數。

InteractiveBrowserCredential 方法

InteractiveBrowserCredential 方法主要用於互動式應用程式,將會開啟網頁瀏覽器進行驗證。 在需要互動式驗證的情況下,您可以使用此方法,而不是 DefaultAzureCredential

若要使用互動式瀏覽器認證,您需要取得對 Azure Digital Twins API 具有權限的應用程式註冊。 如需如何設定此應用程式註冊的步驟,請參閱建立具有 Azure Digital Twins 存取權的應用程式註冊。 設定應用程式註冊之後,您需要...

以下程式碼示範使用 InteractiveBrowserCredential 建立已驗證的 SDK 用戶端。

public class InteractiveBrowserCredentialSample
{
    // Your client / app registration ID
    private const string clientId = "<your-client-ID>";
    // Your tenant / directory ID
    private const string tenantId = "<your-tenant-ID>";
    // The URL of your instance, starting with the protocol (https://)
    private const string adtInstanceUrl = "https://<your-Azure-Digital-Twins-instance-URL>";

    internal void RunSample()
    {
        //...

        DigitalTwinsClient client;
        try
        {
            var credential = new InteractiveBrowserCredential(tenantId, clientId);
            client = new DigitalTwinsClient(new Uri(adtInstanceUrl), credential);
        }
        catch (Exception e)
        {
            Console.WriteLine($"Authentication or client creation error: {e.Message}");
            Environment.Exit(0);
        }
    }
}

注意

雖然您可以將用戶端識別碼、租用戶識別碼和執行個體 URL 直接放入程式碼中,如上所示,但最好改為讓程式碼從組態檔或環境變數取得這些值。

驗證 Azure Functions

本節包含使用 Azure Functions 進行驗證時的一些重要設定選擇。 首先,您將了解建議的類別層級變數和驗證程式碼,以允許函式存取 Azure Digital Twins。 然後,您將了解在函式的程式碼發佈至 Azure 之後,需要完成的一些最終設定步驟。

撰寫應用程式的程式碼

撰寫 Azure 函式時,請考慮將這些變數和程式碼新增至您的函式:

  • 以環境變數或組態設定來讀取 Azure Digital Twins 服務 URL 的程式碼。 最好從應用程式設定/環境變數讀取服務 URL,而不是寫入函式的程式碼中。 在 Azure 函式中,讀取環境變數的程式碼可能如下所示:

    private static readonly string adtInstanceUrl = Environment.GetEnvironmentVariable("ADT_SERVICE_URL");
    

    稍後,發佈函式之後,您將建立並設定環境變數的值,以供此程式碼讀取。 如需相關指示,請直接跳到進行應用程式設定

  • 用來保存 HttpClient 執行個體的靜態變數。 建立 HttpClient 的成本相當高,建議在驗證程式碼中建立一次,以免每次叫用函式時都要建立。

    private static readonly HttpClient singletonHttpClientInstance = new HttpClient();
    
  • 受控識別認證。 建立受控識別認證供函式用來存取 Azure Digital Twins。

    // To use the function app's system-assigned identity:
    var cred = new ManagedIdentityCredential();
    // To use a user-assigned identity for the function app:
    //var cred = new ManagedIdentityCredential("<uai-client-ID>");
    

    如果函式應用程式的系統指派身分識別具有認證,請將參數保留空白,如上所示。 若要改為指定使用者指派的身分識別,請將使用者指派的身分識別用戶端識別碼傳遞至參數。

    稍後,發佈函式之後,您將確定函式的身分識別有權限存取 Azure Digital Twins API。 如需相關指示,請直接跳到指派存取角色

  • 區域變數 DigitalTwinsClient 在函式內新增變數以保存 Azure Digital Twins 用戶端執行個體。 在類別內,「請勿」將此變數設為靜態。

    var client = new DigitalTwinsClient(
        new Uri(adtInstanceUrl),
        cred,
        new DigitalTwinsClientOptions
        {
            Transport = new HttpClientTransport(singletonHttpClientInstance)
        });
    
  • adtInstanceUrl 的 Null 檢查。 新增 Null 檢查,然後將函式邏輯包裝在 try/catch 區塊中,以攔截任何例外狀況。

將這些變數新增至函式之後,您的函式程式碼看起來可能如下列範例所示。

// Default URL for triggering event grid function in the local environment.
// http://localhost:7071/runtime/webhooks/EventGrid?functionName={functionname}
//<Function_dependencies>
using Azure.Core.Pipeline;
using Azure.DigitalTwins.Core;
using Azure.Identity;
using Azure.Messaging.EventGrid;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.EventGrid;
using Microsoft.Extensions.Logging;
using System;
using System.Net.Http;
//</Function_dependencies>

namespace DigitalTwins_Samples
{
    public class DigitalTwinsIngestFunctionSample
    {
        // Your Digital Twin URL is stored in an application setting in Azure Functions
        // <ADT_service_URL>
        private static readonly string adtInstanceUrl = Environment.GetEnvironmentVariable("ADT_SERVICE_URL");
        // </ADT_service_URL>
        // <HTTP_client>
        private static readonly HttpClient singletonHttpClientInstance = new HttpClient();
        // </HTTP_client>

        [FunctionName("TwinsFunction")]
        public void Run([EventGridTrigger] EventGridEvent eventGridEvent, ILogger log)
        {
            log.LogInformation(eventGridEvent.Data.ToString());
            if (adtInstanceUrl == null) log.LogError("Application setting \"ADT_SERVICE_URL\" not set");
            try
            {
                // Authenticate with Digital Twins
                // <ManagedIdentityCredential>
                // To use the function app's system-assigned identity:
                var cred = new ManagedIdentityCredential();
                // To use a user-assigned identity for the function app:
                //var cred = new ManagedIdentityCredential("<uai-client-ID>");
                // </ManagedIdentityCredential>
                // <DigitalTwinsClient>
                var client = new DigitalTwinsClient(
                    new Uri(adtInstanceUrl),
                    cred,
                    new DigitalTwinsClientOptions
                    {
                        Transport = new HttpClientTransport(singletonHttpClientInstance)
                    });
                // </DigitalTwinsClient>
                log.LogInformation($"ADT service client connection created.");

                // Add your business logic here.
            }
            catch (Exception e)
            {
                log.LogError(e.Message);
            }
        }
    }
}

完成函式程式碼後,包括新增驗證和函式的邏輯,請將應用程式發佈至 Azure

設定已發佈的應用程式

最後,對已發佈的 Azure 函式完成下列設定步驟,以確保可以存取您的 Azure Digital Twins 執行個體。

Azure Cloud Shell本機 Azure CLI 中執行下列命令。

注意

此區段必須由有權限管理使用者對 Azure 資源存取權的 Azure 使用者來完成,包括授與和委派權限。 符合此需求的常見角色包括:擁有者帳戶管理員,或使用者存取管理員參與者的組合。 如需 Azure Digital Twins 角色權限需求的詳細資訊,請參閱設定執行個體和驗證

指派存取角色

Azure 函數需要傳遞給角色的持有人權杖。 若要確定已傳遞持有人權杖,請為函數應用程式授與 Azure Digital Twins 執行個體的 Azure Digital Twins 資料擁有者角色,這會授與函數應用程式在執行個體上執行資料平面活動的權限。

  1. 使用下列命令來為函式建立 系統受控識別 (如果函式已經有,此命令將會列印其詳細資料)。 記下輸出中的 principalId 欄位。 您將使用此識別碼來參考函數,以便可以在下一個步驟中授與其權限。

    az functionapp identity assign --resource-group <your-resource-group> --name <your-function-app-name>	
    
  2. 使用下列命令中的 principalId 值,將函數提供給您 Azure Digital Twins 執行個體的 Azure Digital Twins 資料擁有者角色。

    az dt role-assignment create --dt-name <your-Azure-Digital-Twins-instance> --assignee "<principal-ID>" --role "Azure Digital Twins Data Owner"
    

設定應用程式設定

接下來,為函數設定環境變數,讓您的 Azure Digital Twins 執行個體的 URL 存取函數。

提示

Azure Digital Twins 執行個體的 URL 是藉由將 https:// 新增至執行個體主機名稱的開頭加以建立。 若要查看主機名稱,以及執行個體的所有屬性,請執行 az dt show --dt-name <your-Azure-Digital-Twins-instance>

下列命令會設定執行個體 URL 的環境變數,每當函數需要存取執行個體時,就會使用該環境變數。

az functionapp config appsettings set --resource-group <your-resource-group> --name <your-function-app-name> --settings "ADT_SERVICE_URL=https://<your-Azure-Digital-Twins-instance-host-name>"

跨租用戶進行驗證

Azure Digital Twins 是僅支援一個 Microsoft Entra 租用戶的服務:來自 Azure Digital Twins 執行個體所在訂用帳戶的主要租用戶。

因此,對 Azure Digital Twins API 提出要求時,使用者或服務主體必須屬於 Azure Digital Twins 執行個體所在的相同租用戶。 為了防止惡意掃描 Azure Digital Twins 端點,從原始租用戶外部要求存取權杖會傳回「404 找不到子網域」錯誤訊息。 即使使用者或服務主體已透過 Microsoft Entra B2B 共同作業獲得 Azure Digital Twins 資料擁有者或 Azure Digital Twins 資料讀者角色,也會傳回此錯誤。

如果您存取 Azure Digital Twins 執行個體時需要使用的服務主體或使用者帳戶,屬於不同於執行個體的租用戶,您可以令另一個租用戶的每個同盟身分識別,從 Azure Digital Twins 執行個體的「主」租用戶要求權杖

方法之一是使用下列 CLI 命令,其中 <home-tenant-ID> 是包含 Azure Digital Twins 執行個體的 Microsoft Entra 租用戶識別碼:

az account get-access-token --tenant <home-tenant-ID> --resource https://digitaltwins.azure.net

提出此要求之後,身分識別會收到發給 https://digitaltwins.azure.net Microsoft Entra 資源的權杖,該權杖具有與 Azure Digital Twins 執行個體相符的租用戶識別碼宣告。 在 API 要求中或透過 Azure.Identity 程式碼使用此權杖,應該就可讓同盟身分識別存取 Azure Digital Twins 資源。

您也可以在程式碼的認證選項中指定主租用戶。

下列範例顯示如何在 DefaultAzureCredential 選項的 InteractiveBrowserTenantId 中設定範例租用戶識別碼值:

public class DefaultAzureCredentialOptionsSample
{
    // The URL of your instance, starting with the protocol (https://)
    private const string adtInstanceUrl = "https://<your-Azure-Digital-Twins-instance-URL>";

    private static DefaultAzureCredentialOptions credentialOptions = new DefaultAzureCredentialOptions()
    {
        ExcludeSharedTokenCacheCredential = true,
        ExcludeVisualStudioCodeCredential = true,
        TenantId = "<your-Azure-Active-Directory-tenant-ID>"
    };

    private static DefaultAzureCredential credential = new DefaultAzureCredential(credentialOptions);

    DigitalTwinsClient client = new DigitalTwinsClient(new Uri(adtInstanceUrl), credential);
}

Visual Studio 和 Visual Studio Code 有類似的選項可設定要驗證的租用戶。 如需可用選項的詳細資訊,請參閱 DefaultAzureCredentialOptions 文件

其他認證方法

如果以上強調的驗證案例不符合您的應用程式需求,您可以探索 Microsoft 身分識別平台中提供的其他驗證類型。 此平台的文件涵蓋更多驗證案例,依應用程式類型編排。

下一步

深入了解 Azure Digital Twins 中的安全性運作方式:

或者,既然已設定驗證,請繼續在執行個體中建立和管理模型: