快速入门:获取令牌并从 Windows 桌面应用中调用 Microsoft Graph APIQuickstart: Acquire a token and call Microsoft Graph API from a Windows desktop app

本快速入门介绍如何编写 Windows 桌面.NET (WPF) 应用程序,该应用程序能够登录工作和学校帐户,获取访问令牌以及调用 Microsoft Graph API。In this quickstart, you'll learn how to write a Windows desktop .NET (WPF) application that can sign in work and school accounts, get an access token, and call the Microsoft Graph API. (有关说明,请参阅示例工作原理。)(See How the sample works for an illustration.)

注册并下载快速入门应用Register and download your quickstart app

可以使用两个选项来启动快速入门应用程序:You have two options to start your quickstart application:

选项 1:注册并自动配置应用,然后下载代码示例Option 1: Register and auto configure your app and then download your code sample

  1. 转到新的 Azure 门户 - 应用注册Go to the new Azure portal - App registrations.
  2. 输入应用程序的名称并选择“注册” 。Enter a name for your application and select Register.
  3. 遵照说明下载内容,并只需单击一下自动配置新应用程序。Follow the instructions to download and automatically configure your new application with just one click.

选项 2:注册并手动配置应用程序和代码示例Option 2: Register and manually configure your application and code sample

步骤 1:注册应用程序Step 1: Register your application

若要手动注册应用程序并将应用的注册信息添加到解决方案,请执行以下步骤:To register your application and add the app's registration information to your solution manually, follow these steps:

  1. 使用工作或学校帐户登录到 Azure 门户Sign in to the Azure portal using a work or school account.
  2. 如果你的帐户有权访问多个租户,请在右上角选择该帐户,并将门户会话设置为所需的 Azure AD 租户。If your account gives you access to more than one tenant, select your account in the top right corner, and set your portal session to the desired Azure AD tenant.
  3. 导航到面向开发人员的 Microsoft 标识平台的应用注册页。Navigate to the Microsoft identity platform for developers App registrations page.
  4. 选择“新注册”。 Select New registration.
    • 在“名称” 部分输入一个会显示给应用用户的有意义的应用程序名称,例如 Win-App-calling-MsGraphIn the Name section, enter a meaningful application name that will be displayed to users of the app, for example Win-App-calling-MsGraph.
    • 在“支持的帐户类型”部分,选择“任何组织目录中的帐户”。 In the Supported account types section, select Accounts in any organizational directory.
    • 选择“注册” 以创建应用程序。Select Register to create the application.
  5. 在应用的页面列表中,选择“身份验证”。 In the list of pages for the app, select Authentication.
  6. 在“重定向 URI” | “建议用于公共客户端(移动、桌面)的重定向 URI” 部分中,使用 https://login.partner.microsoftonline.cn/common/oauth2/nativeclientIn the Redirect URIs | Suggested Redirect URIs for public clients (mobile, desktop) section, use https://login.partner.microsoftonline.cn/common/oauth2/nativeclient.
  7. 选择“保存” 。Select Save.

步骤 1:在 Azure 门户中配置应用程序Step 1: Configure your application in Azure portal

要使此快速入门的代码示例正常运行,需要将答复 URL 添加为 https://login.partner.microsoftonline.cn/common/oauth2/nativeclientFor the code sample for this quickstart to work, you need to add a reply URL as https://login.partner.microsoftonline.cn/common/oauth2/nativeclient.

已配置 应用程序已使用这些属性进行配置。Already configured Your application is configured with these attributes.

步骤 2:下载 Visual Studio 项目Step 2: Download your Visual Studio project

使用 Visual Studio 2019 运行项目。Run the project using Visual Studio 2019.

步骤 3:应用已配置并可以运行Step 3: Your app is configured and ready to run

我们已经为项目配置了应用属性的值,并且该项目已准备好运行。We have configured your project with values of your app's properties and it's ready to run.

Note

Enter_the_Supported_Account_Info_Here

步骤 3:配置 Visual Studio 项目Step 3: Configure your Visual Studio project

  1. 将 zip 文件提取到靠近磁盘根目录的本地文件夹,例如 C:\Azure-SamplesExtract the zip file to a local folder close to the root of the disk, for example, C:\Azure-Samples.

  2. 在 Visual Studio 中打开项目。Open the project in Visual Studio.

  3. 编辑 App.Xaml.cs 并将字段 ClientIdTenant 的值替换为以下代码:Edit App.Xaml.cs and replace the values of the fields ClientId and Tenant with the following code:

    private static string ClientId = "Enter_the_Application_Id_here";
    private static string Tenant = "Enter_the_Tenant_Info_Here";
    

其中:Where:

  • Enter_the_Application_Id_here - 是已注册应用程序的应用程序(客户端)IDEnter_the_Application_Id_here - is the Application (client) ID for the application you registered.
  • Enter_the_Tenant_Info_Here - 设置为以下选项之一:Enter_the_Tenant_Info_Here - is set to one of the following options:
    • 如果应用程序支持“此组织目录中的帐户” ,请将该值替换为租户 ID租户名称(例如 contoso.microsoft.com)If your application supports Accounts in this organizational directory, replace this value with the Tenant Id or Tenant name (for example, contoso.microsoft.com)
    • 如果应用程序支持“任何组织目录中的帐户”,请将该值替换为 organizationsIf your application supports Accounts in any organizational directory, replace this value with organizations

Tip

若要查找“应用程序(客户端) ID”、“目录(租户) ID”和“支持的帐户类型”的值,请转到 Azure 门户中应用的“概述”页。 To find the values of Application (client) ID, Directory (tenant) ID, and Supported account types, go to the app's Overview page in the Azure portal.

详细信息More information

示例工作原理How the sample works

显示本快速入门生成的示例应用的工作原理

MSAL.NETMSAL.NET

MSAL (Microsoft.Identity.Client) 是一个库,用于用户登录和请求令牌,此类令牌用于访问受 Microsoft 标识平台保护的 API。MSAL (Microsoft.Identity.Client) is the library used to sign in users and request tokens used to access an API protected by Microsoft identity platform. 可在 Visual Studio 的包管理器控制台中运行以下命令,以便安装 MSAL :You can install MSAL by running the following command in Visual Studio's Package Manager Console:

Install-Package Microsoft.Identity.Client -IncludePrerelease

MSAL 初始化MSAL initialization

可以通过添加以下代码,为 MSAL 添加引用:You can add the reference for MSAL by adding the following code:

using Microsoft.Identity.Client;

然后,使用以下代码对 MSAL 进行初始化:Then, initialize MSAL using the following code:

public static IPublicClientApplication PublicClientApp;
PublicClientApplicationBuilder.Create(ClientId)
                .WithRedirectUri("https://login.partner.microsoftonline.cn/common/oauth2/nativeclient")
                .WithAuthority(AzureCloudInstance.AzureChina, Tenant)
                .Build();
其中:Where:
ClientId 是在 Azure 门户中注册的应用程序的应用程序(客户端) IDIs the Application (client) ID for the application registered in the Azure portal. 可以在 Azure 门户的应用的“概览” 页中找到此值。You can find this value in the app's Overview page in the Azure portal.

请求令牌Requesting tokens

MSAL 有两种获取令牌的方法:AcquireTokenInteractiveAcquireTokenSilentMSAL has two methods for acquiring tokens: AcquireTokenInteractive and AcquireTokenSilent.

以交互方式获取用户令牌Get a user token interactively

某些情况下需要强制用户通过弹出窗口与 Microsoft 标识平台终结点进行交互,以验证其凭据或进行许可。Some situations require forcing users interact with the Microsoft identity platform endpoint through a popup window to either validate their credentials or to give consent. 示例包括:Some examples include:

  • 用户首次登录应用程序The first time users sign in to the application
  • 由于密码已过期,用户可能需要重新输入凭据的情况When users may need to reenter their credentials because the password has expired
  • 应用程序正在请求访问用户需要同意的资源的情况When your application is requesting access to a resource that the user needs to consent to
  • 需要双重身份验证的情况When two factor authentication is required
authResult = await App.PublicClientApp.AcquireTokenInteractive(_scopes)
                                      .ExecuteAsync();
其中:Where:
_scopes 包含所请求的作用域,例如针对 Microsoft Graph 的 { "https://microsoftgraph.chinacloudapi.cn/user.read" } 或针对自定义 Web API 的 { "api://<Application ID>/access_as_user" }Contains the scopes being requested, such as { "https://microsoftgraph.chinacloudapi.cn/user.read" } for Microsoft Graph or { "api://<Application ID>/access_as_user" } for custom Web APIs.

以无提示方式获取用户令牌Get a user token silently

你不希望在用户每次需要访问资源时都要求其验证其凭据。You don't want to require the user to validate their credentials every time they need to access a resource. 大多数情况下,你希望在无需任何用户交互的情况下进行令牌获取和续订。Most of the time you want token acquisitions and renewal without any user interaction. 可以使用 AcquireTokenSilent 方法获取令牌,以在初始 AcquireTokenInteractive 方法后访问受保护资源:You can use the AcquireTokenSilent method to obtain tokens to access protected resources after the initial AcquireTokenInteractive method:

var accounts = await App.PublicClientApp.GetAccountsAsync();
var firstAccount = accounts.FirstOrDefault();
authResult = await App.PublicClientApp.AcquireTokenSilent(scopes, firstAccount)
                                      .ExecuteAsync();
其中:Where:
scopes 包含所请求的作用域,例如针对 Microsoft Graph 的 { "https://microsoftgraph.chinacloudapi.cn/user.read" } 或针对自定义 Web API 的 { "api://<Application ID>/access_as_user" }Contains the scopes being requested, such as { "https://microsoftgraph.chinacloudapi.cn/user.read" } for Microsoft Graph or { "api://<Application ID>/access_as_user" } for custom Web APIs.
firstAccount 指定缓存中的第一个用户(MSAL 支持单个应用中的多个用户)。Specifies the first user in the cache (MSAL support multiple users in a single app).

帮助和支持Help and support

如果需要帮助、需要报告问题,或者需要详细了解支持选项,请参阅以下文章:If you need help, want to report an issue, or want to learn more about your support options, see the following article:

后续步骤Next steps

试用 Windows 桌面教程,了解有关构建应用程序和新功能的完整分布指南,包括本快速入门的完整说明。Try out the Windows desktop tutorial for a complete step-by-step guide on building applications and new features, including a full explanation of this quickstart.