快速入门:从通用 Windows 平台 (UWP) 应用程序调用 Microsoft Graph APIQuickstart: Call the Microsoft Graph API from a Universal Windows Platform (UWP) application

本快速入门包含了一个代码示例,该示例演示了通用 Windows 平台 (UWP) 应用程序如何让用户使用工作和学校帐户进行登录,获取访问令牌以及调用 Microsoft Graph API。This quickstart contains a code sample that demonstrates how a Universal Windows Platform (UWP) application can sign in users with 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 pane.
  2. 输入应用程序的名称,然后单击“注册”。Enter a name for your application and click Register.
  3. 遵照说明下载内容,并一键式自动配置新应用程序。Follow the instructions to download and automatically configure your new application for you in 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, 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.
  5. “注册应用程序”页出现后,请输入应用程序的注册信息:When the Register an application page appears, enter your application's registration information:
    • 在“名称”部分输入一个会显示给应用用户的有意义的应用程序名称,例如 UWP-App-calling-MsGraphIn the Name section, enter a meaningful application name that will be displayed to users of the app, for example UWP-App-calling-MsGraph.
    • 在“支持的帐户类型”部分,选择“任何组织目录中的帐户”。 In the Supported account types section, select Accounts in any organizational directory.
    • 选择“注册”以创建应用程序。Select Register to create the application.
  6. 在应用的页面列表中,选择“身份验证”。In the list of pages for the app, select Authentication.
  7. 在“重定向 URI” | “建议用于公共客户端(移动、桌面)的重定向 URI”部分中,选中 https://login.partner.microsoftonline.cn/common/oauth2/nativeclientIn the Redirect URIs | Suggested Redirect URIs for public clients (mobile, desktop) section, check https://login.partner.microsoftonline.cn/common/oauth2/nativeclient.
  8. 选择“保存”。Select Save.

步骤 1:配置应用程序Step 1: Configure your application

要使此快速入门的代码示例正常运行,需要将重定向 URI 添加为 https://login.partner.microsoftonline.cn/common/oauth2/nativeclientFor the code sample for this quickstart to work, you need to add a redirect URI 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.

备注

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. 系统可能会提示你安装 UWP SDK。You might be prompted to install a UWP SDK. 在这种情况下,请接受。In that case, accept.

  3. 编辑 MainPage.Xaml.cs,替换 ClientId 字段的值:Edit MainPage.Xaml.cs and replace the values of the ClientId field:

    private const string ClientId = "Enter_the_Application_Id_here";
    

其中:Where:

  • Enter_the_Application_Id_here - 是已注册应用程序的应用程序 ID。Enter_the_Application_Id_here - is the Application Id for the application you registered.

提示

若要查找“应用程序 ID”的值,请转到门户中的“概览”部分To find the value of Application ID, go to the Overview section in the portal

步骤 4:运行应用程序Step 4: Run your application

若要在 Windows 计算机上尝试快速入门,请执行以下操作:If you want to try the quickstart on your Windows machine:

  1. 在 Visual Studio 工具栏中,选择适当的平台(可能为 x64x86,不是 ARM)。In the Visual Studio toolbar, choose the right platform (probably x64 or x86, not ARM). 你将看到目标设备从“设备”更改为“本地计算机”You will observe that the target device changes from Device to Local Machine
  2. 选择“调试”|“在不调试的情况下启动”Select Debug | Start Without Debugging

详细信息More information

此部分提供快速入门的详细信息。This section provides more information about the quickstart.

示例工作原理How the sample works

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

MSAL.NETMSAL.NET

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

Install-Package Microsoft.Identity.Client

MSAL 初始化MSAL initialization

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

using Microsoft.Identity.Client;

然后,系统将使用以下代码对 MSAL 进行初始化:Then, MSAL is initialized using the following code:

public static IPublicClientApplication PublicClientApp;
PublicClientApp = PublicClientApplicationBuilder.Create(ClientId)
                                                .WithRedirectUri("https://login.partner.microsoftonline.cn/common/oauth2/nativeclient")
                                                    .Build();
其中: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 有两种在 UWP 应用中获取令牌的方法:AcquireTokenInteractiveAcquireTokenSilentMSAL has two methods for acquiring tokens in a UWP app: AcquireTokenInteractive and AcquireTokenSilent.

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

在某些情况下需要强制用户通过弹出窗口与 Microsoft 标识平台终结点进行交互,以验证其凭据或进行许可。Some situations require forcing users to 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: 说明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

使用 AcquireTokenSilent 方法可获取令牌,以在初始 AcquireTokenInteractive 方法后访问受保护资源。Use the AcquireTokenSilent method to obtain tokens to access protected resources after the initial AcquireTokenInteractive method. 你不希望在用户每次需要访问资源时都要求其验证其凭据。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

var accounts = await App.PublicClientApp.GetAccountsAsync();
var firstAccount = accounts.FirstOrDefault();
authResult = await App.PublicClientApp.AcquireTokenSilent(scopes, firstAccount)
                                      .ExecuteAsync();
其中: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 account in the cache (MSAL supports multiple users in a single app)

帮助和支持Help and support

如果需要帮助、需要报告问题,或者需要详细了解支持选项,请参阅面向开发人员的帮助和支持If you need help, want to report an issue, or would like 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.