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

在本快速入门中,你将下载并运行一个代码示例,该示例演示 Windows desktop .NET (WPF) 应用程序如何让用户登录并获取访问令牌来调用 Microsoft Graph API。In this quickstart, you download and run a code sample that demonstrates how a Windows desktop .NET (WPF) application can sign in users and get an access token to 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 Azure portal - App registrations quickstart experience.
  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.
  2. 如果有权访问多个租户,请使用顶部菜单中的“目录 + 订阅”筛选器 ,选择要在其中注册应用程序的租户。
  3. 搜索并选择“Azure Active Directory”。Search for and select Azure Active Directory.
  4. 在“管理”下,选择“应用注册” > “新建注册” 。Under Manage, select App registrations > New registration.
  5. 输入应用程序的名称(例如 Win-App-calling-MsGraph)。Enter a Name for your application, for example Win-App-calling-MsGraph. 应用的用户可能会看到此名称,你稍后可对其进行更改。Users of your app might see this name, and you can change it later.
  6. 在“支持的帐户类型”部分,选择“任何组织目录中的帐户”。 In the Supported account types section, select Accounts in any organizational directory.
  7. 选择“注册”以创建应用程序。Select Register to create the application.
  8. 在“管理”下,选择“身份验证”。 Under Manage, select Authentication.
  9. 选择“添加平台” > “移动和桌面应用程序” 。Select Add a platform > Mobile and desktop applications.
  10. 在“重定向 URI”部分中,选择 https://login.partner.microsoftonline.cn/common/oauth2/nativeclient,然后在“自定义重定向 URI”中添加 ms-appx-web://microsoft.aad.brokerplugin/{client_id},其中 {client_id} 是应用程序的应用程序(客户端)ID(与 msal{client_id}://auth 复选框中显示的 GUID 相同) 。In the Redirect URIs section, select https://login.partner.microsoftonline.cn/common/oauth2/nativeclient and in Custom redirect URIs add ms-appx-web://microsoft.aad.brokerplugin/{client_id} where {client_id} is the application (client) ID of your application (the same GUID that appears in the msal{client_id}://auth checkbox).
  11. 选择“配置” 。Select Configure.

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

为使此快速入门中的代码示例正常运行,请添加重定向 URI https://login.partner.microsoftonline.cn/common/oauth2/nativeclientms-appx-web://microsoft.aad.brokerplugin/{client_id}For the code sample in this quickstart to work, add a Redirect URI of https://login.partner.microsoftonline.cn/common/oauth2/nativeclient and ms-appx-web://microsoft.aad.brokerplugin/{client_id}.

已配置 应用程序已使用这些属性进行配置。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.


为了避免在 Windows 中出现路径长度限制导致的错误,建议将存档解压或将存储库克隆到驱动器根附近的目录中。To avoid errors caused by path length limitations in Windows, we recommend extracting the archive or cloning the repository into a directory near the root of your drive.

步骤 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.



步骤 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";


  • Enter_the_Application_Id_here - 是已注册应用程序的 应用程序(客户端)IDEnter_the_Application_Id_here - is the Application (client) ID for the application you registered.

    若要查找“应用程序(客户端) ID”的值,请转到 Azure 门户中应用的“概述”页 。To find the value of Application (client) ID, go to the app's Overview page in the Azure portal.

  • 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

      若要查找“目录(租户) ID”和“支持的帐户类型”的值,请转到 Azure 门户中应用的“概述”页。 To find the values of 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 (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;
                .WithAuthority(AzureCloudInstance.AzureChina, Tenant)
其中:Where: 说明Description
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 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)
其中:Where: 说明Description
_scopes 包含所请求的范围,例如 { "https://microsoftgraph.chinacloudapi.cn/user.read" }(针对 Microsoft Graph)或 { "api://<Application ID>/access_as_user" }(针对自定义 Web API)。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)
其中:Where: 说明Description
scopes 包含所请求的范围,例如 { "https://microsoftgraph.chinacloudapi.cn/user.read" }(针对 Microsoft Graph)或 { "api://<Application ID>/access_as_user" }(针对自定义 Web API)。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 about your support options, see Help and support for developers.

后续步骤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.