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

設定 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 撰寫的內容,但不論您使用的 SDK 為何,都可以使用 Azure.Identity 版本(如需 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 ,以設定範例的認證。

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

ManagedIdentityCredential 方法

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

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

若要使用預設的 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 使用者完成,包括授與和委派許可權。 符合此需求的常見角色包括 擁有者 帳戶管理員 或使用者存取管理員istrator 參與者 的組合 。 如需 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 中的安全性運作方式:

或者,現在已設定驗證,請繼續在您的實例中建立和管理模型: