您现在访问的是微软AZURE全球版技术文档网站,若需要访问由世纪互联运营的MICROSOFT AZURE中国区技术文档网站,请访问 https://docs.azure.cn.

编写客户端应用身份验证代码Write client app authentication code

设置 Azure 数字孪生实例和身份验证后,可以创建将用于与实例进行交互的客户端应用程序。After you set up an Azure Digital Twins instance and authentication, you can create a client application that you will use to interact with the instance. 设置入门客户端项目后,本文将介绍如何在该客户端应用程序中编写代码,以便对 Azure 数字孪生实例进行身份验证。Once you have set up a starter client project, this article shows you how to write code in that client app to authenticate it against the Azure Digital Twins instance.

本文提供了两种方法来示例代码。There are two approaches to sample code in this article. 您可以根据自己的选择,使用最适合自己的语言:You can use the one that's right for you, depending on your language of choice:

你还可以在操作方法:使用 Azure 数字孪生 api 和 sdk中了解有关 Azure 数字孪生的 Api 和 sdk 的详细信息。You can also read more about the APIs and SDKs for Azure Digital Twins in How-to: Use the Azure Digital Twins APIs and SDKs.

先决条件Prerequisites

首先,请完成操作方法:设置实例和身份验证中的设置步骤。First, complete the setup steps in How-to: Set up an instance and authentication. 这将确保你有 Azure 数字孪生实例,你的用户具有访问权限,并且已为客户端应用程序设置了权限。This will ensure you have an Azure Digital Twins instance, your user has access permissions, and you've set up permissions for client applications. 完成此设置后,就可以编写客户端应用代码了。After all this setup, you are ready to write client app code.

若要继续,你需要一个客户端应用程序项目,可在其中编写代码。To proceed, you will need a client app project in which you write your code. 如果尚未设置客户端应用程序项目,请使用与本教程一起使用的所选语言创建基本项目。If you don't already have a client app project set up, create a basic project in your language of choice to use with this tutorial.

身份验证和客户端创建: .NET (c #) SDKAuthentication and client creation: .NET (C#) SDK

首先,在项目中包括以下包,以便将 .NET SDK 和身份验证工具用于本操作方法:First, include the following packages in your project in order to use the .NET SDK and authentication tools for this how-to:

  • Azure.DigitalTwins.Core(版本 1.0.0-preview.2Azure.DigitalTwins.Core (version 1.0.0-preview.2)
  • Azure.Identity

根据您选择的工具,您可以使用 Visual Studio 包管理器或 dotnet 命令行工具包含包。Depending on your tools of choice, you can include the packages using the Visual Studio package manager or the dotnet command line tool.

若要使用 .NET SDK 进行身份验证,请使用在Azure中定义的凭据获取方法之一。To authenticate with the .NET SDK, use one of the credential-obtaining methods that are defined in the Azure.Identity library.

下面是常用的两种:Here are two that are commonly used:

还需要以下 using 语句:You'll also need the following using statements:

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

若要使用交互式浏览器凭据创建经过身份验证的 SDK 客户端,请添加以下代码:To use the interactive browser credentials to create an authenticated SDK client, add this code:

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

//...

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

备注

虽然你可以将客户端 ID、租户 ID 和实例 URL 直接放置在代码中(如上所示),但最好是让你的代码从配置文件或环境变量获取这些值。While you can place the client ID, tenant ID and instance URL directly into the code as shown above, it's a good idea to have your code get these values from a configuration file or environment variable instead.

在 Azure 函数中,可以使用如下所示的托管标识凭据:In an Azure function, you can then use the managed identity credentials like this:

ManagedIdentityCredential cred = new ManagedIdentityCredential(adtAppId);
DigitalTwinsClientOptions opts = 
    new DigitalTwinsClientOptions { Transport = new HttpClientTransport(httpClient) });
client = new DigitalTwinsClient(new Uri(adtInstanceUrl), cred, opts);

请参阅如何:设置用于处理数据的 Azure 函数以获取更完整的示例,该示例介绍函数上下文中的一些重要配置选项。See How-to: Set up an Azure function for processing data for a more complete example that explains some of the important configuration choices in the context of functions.

此外,若要在函数中使用身份验证,请记住:Also, to use authentication in a function, remember to:

使用 AutoRest 生成的 SDK 进行身份验证Authentication with an AutoRest-generated SDK

如果使用的不是 .NET,则可以选择使用所选的语言构建 SDK 库,如操作方法:使用 AutoRest 创建 Azure 数字孪生的自定义 sdk中所述。If you are not using .NET, you may opt to build an SDK library in a language of your choice, as described in How-to: Create custom SDKs for Azure Digital Twins with AutoRest.

本部分介绍如何在这种情况下进行身份验证。This section explains how to authenticate in that case.

先决条件Prerequisites

首先,应完成使用 AutoRest :使用 AutoRest 创建 Azure 数字孪生的自定义sdk 中的步骤,创建包含的自定义 SDK 的步骤。First, you should complete the steps to create a custom SDK with AutoRest, using the steps in How-to: Create custom SDKs for Azure Digital Twins with AutoRest.

此示例使用通过 AutoRest 生成的 Typescript SDK。This example uses a Typescript SDK generated with AutoRest. 因此,它还需要:As a result, it also requires:

最小身份验证代码示例Minimal authentication code sample

若要使用 Azure 服务对应用进行身份验证,你可以在客户端应用中使用以下最少代码。To authenticate an app with Azure services, you can use the following minimal code within your client app.

你将需要之前的应用程序(客户端) id目录(租户) Id以及 Azure 数字孪生实例的 URL。You will need your Application (client) ID and Directory (tenant) ID from earlier, as well as the URL of your Azure Digital Twins instance.

提示

Azure 数字孪生实例的 URL 是通过将https:// 添加到 Azure 数字孪生实例的主机名的开头来完成的。The Azure Digital Twins instance's URL is made by adding https:// to the beginning of your Azure Digital Twins instance's hostName. 若要查看主机名以及实例的所有属性,可以运行 az dt show --dt-name <your-Azure-Digital-Twins-instance>To see the hostName, along with all the properties of your instance, you can run az dt show --dt-name <your-Azure-Digital-Twins-instance>. 可以使用 az account show --query tenantId 命令查看目录(租户) IDYou can use the az account show --query tenantId command to see your Directory (tenant) ID.

import * as Msal from "msal";
import { TokenCredentials } from "@azure/ms-rest-js";
// Autorest-generated SDK
import { AzureDigitalTwinsAPI } from './azureDigitalTwinsAPI';

// Client / app registration ID
var ClientId = "<your-client-ID>";
// Azure tenant / directory ID
var TenantId = "<your-tenant-ID>";
// URL of the Azure Digital Twins instance
var AdtInstanceUrl = "<your-instance-URL>"; 

var AdtAppId = "https://digitaltwins.azure.net";

let client = null;

export async function login() {

    const msalConfig = {
        auth: {
            clientId: ClientId,
            redirectUri: "http://localhost:3000",
            authority: "https://login.microsoftonline.com/"+TenantId
        }
    };

    const msalInstance = new Msal.UserAgentApplication(msalConfig);

    msalInstance.handleRedirectCallback((error, response) => {
        // handle redirect response or error
    });

    var loginRequest = {
        scopes: [AdtAppId + "/.default"] 
    };

    try {
        await msalInstance.loginPopup(loginRequest)
        var accessToken;
        // if the user is already logged in you can acquire a token
        if (msalInstance.getAccount()) {
            var tokenRequest = {
                scopes: [AdtAppId + "/.default"]
            };
            try {
                const response = await msalInstance.acquireTokenSilent(tokenRequest);
                accessToken = response.accessToken;
            } catch (err) {
                if (err.name === "InteractionRequiredAuthError") {
                    const response = await msalInstance.acquireTokenPopup(tokenRequest)
                    accessToken = response.accessToken;
                }
            }
        }
        if (accessToken!=null)
        {
            var tokenCredentials = new TokenCredentials(accessToken);
                
            // Add token and server URL to service instance
            const clientConfig = {
                baseUri: AdtInstanceUrl
            };
            client = new AzureDigitalTwinsAPI(tokenCredentials, clientConfig);
            appDataStore.client = client;
        }
    } catch (err) {
        ...
    }
}

请注意,上面的代码会将客户端 ID、租户 ID 和实例 URL 直接放置在代码中,这是一个很好的做法,就是让代码改为从配置文件或环境变量获取这些值。Note again that where the code above places the client ID, tenant ID and instance URL directly into the code for simplicity, it's a good idea to have your code get these values from a configuration file or environment variable instead.

MSAL 有更多选项可用于实现缓存和其他身份验证流等功能。MSAL has many more options you can use, to implement things like caching and other authentication flows. 有关此内容的详细信息,请参阅Microsoft 身份验证库概述(MSAL)For more information on this, see Overview of Microsoft Authentication Library (MSAL).

后续步骤Next steps

详细了解如何在 Azure 数字孪生中运行安全性:Read more about how security works in Azure Digital Twins:

或者,现在已经设置了身份验证,请转到在实例中创建模型:Or, now that authentication is set up, move on to creating models in your instance: