快速入门:构建集成 Microsoft 登录的 Xamarin 应用Quickstart: Build a Xamarin app that integrates Microsoft sign-in

适用于:Applies to:
  • Azure AD v1.0 终结点Azure AD v1.0 endpoint
  • Azure Active Directory Authentication Library (ADAL)Azure Active Directory Authentication Library (ADAL)

借助 Xamarin,可以使用 C# 编写可在 iOS、Android 和 Windows(移动设备和电脑)上运行的移动应用。With Xamarin, you can write mobile apps in C# that can run on iOS, Android, and Windows (mobile devices and PCs). 如果使用 Xamarin 构建应用,可以通过 Azure Active Directory (Azure AD) 轻松使用用户的 Active Directory 帐户对其进行身份验证。If you're building an app using Xamarin, Azure Active Directory (Azure AD) makes it simple to authenticate users with their Azure AD accounts. 该应用还能安全使用 Azure AD 保护的任何 Web API,例如 Office 365 API 或 Azure API。The app can also securely consume any web API that's protected by Azure AD, such as the Office 365 APIs or the Azure API.

对于需要访问受保护资源的 Xamarin 应用程序,Azure AD 提供 Active Directory 身份验证库 (ADAL)。For Xamarin apps that need to access protected resources, Azure AD provides the Active Directory Authentication Library (ADAL). 在本质上,ADAL 的唯一用途就是方便应用获取访问令牌。The sole purpose of ADAL is to make it easy for apps to get access tokens. 为了演示操作的简单性,本文介绍如何构建 DirectorySearcher 应用,该应用可以:To demonstrate how easy it is, this article shows how to build DirectorySearcher apps that:

  • 在 iOS、Android、Windows 桌面、Windows Phone 和 Windows 应用商店上运行。Run on iOS, Android, Windows Desktop, Windows Phone, and Windows Store.
  • 使用单个可移植类库 (PCL) 对用户进行身份验证,并获取 Azure AD 图形 API 的令牌。Use a single portable class library (PCL) to authenticate users and get tokens for the Azure AD Graph API.
  • 在目录中搜索具有给定 UPN 的用户。Search a directory for users with a given UPN.

先决条件Prerequisites

准备好后,请按照以下 4 个部分中的步骤操作。When you are ready, follow the procedures in the next four sections.

步骤 1:设置 Xamarin 开发环境Step 1: Set up your Xamarin development environment

由于本教程包含 iOS、Android 和 Windows 的项目,因此需要 Visual Studio 和 Xamarin。Because this tutorial includes projects for iOS, Android, and Windows, you need both Visual Studio and Xamarin. 若要创建所需的环境,请完成 MSDN 上设置和安装 Visual Studio 与 Xamarin 中的过程。To create the necessary environment, complete the process in Set up and install Visual Studio and Xamarin on MSDN. 这些说明包含的材料可供你在等待安装完成时查看,以深入了解 Xamarin。The instructions include material that you can review to learn more about Xamarin while you're waiting for the installations to be completed.

完成设置后,在 Visual Studio 中打开解决方案。After you've completed the setup, open the solution in Visual Studio. 可以看到六个项目:五个特定于平台的项目,一个要在所有平台之间共享的 PCL,即 DirectorySearcher.cs。There, you will find six projects: five platform-specific projects and one PCL, DirectorySearcher.cs, which will be shared across all platforms.

步骤 2:注册 DirectorySearcher 应用Step 2: Register the DirectorySearcher app

若要让应用获取令牌,首先需要在 Azure AD 租户中注册该应用,并授予其访问 Azure AD 图形 API 的权限。To enable the app to get tokens, you first need to register it in your Azure AD tenant and grant it permission to access the Azure AD Graph API. 方法如下:Here's how:

  1. 登录到 Azure 门户Sign in to the Azure portal.
  2. 在顶部栏上,单击帐户。On the top bar, click your account. 然后,在“目录”列表下选择要注册应用的 Active Directory 租户。Then, under the Directory list, select the Active Directory tenant where you want to register the app.
  3. 在左窗格中,单击“所有服务”,并选择“Azure Active Directory”。Click All services in the left pane, and then select Azure Active Directory.
  4. 单击“应用注册”,然后选择“新建应用程序注册”。Click App registrations, and then select New application registration.
  5. 创建新的本机应用程序。Create a new Native Application.
    • 名称 - 向用户描述应用。Name describes the app to users.
    • 重定向 URI 是 Azure AD 用来返回令牌响应的方案与字符串组合。Redirect URI is a scheme and string combination that Azure AD uses to return token responses. 输入值 (例如 http://DirectorySearcher) 。Enter a value (for example, http://DirectorySearcher).
  6. 完成注册后,Azure AD 将为应用分配唯一的应用程序 ID。After you’ve completed registration, Azure AD assigns the app a unique application ID. 复制“应用程序”选项卡中的值,因为稍后需用到此值。Copy the value from the Application tab, because you'll need it later.
  7. 在“设置”页上,选择“所需权限”,并选择“添加”。On the Settings page, select Required Permissions, and then select Add.
  8. 选择“Microsoft Graph”作为 API。Select Microsoft Graph as the API. 在“委派权限”下面,添加“读取目录数据”权限。Under Delegated Permissions, add the Read Directory Data permission. 此操作可让应用查询用户的图形 API。This action enables the app to query the Graph API for users.

步骤 3:安装并配置 ADALStep 3: Install and configure ADAL

将应用注册到 Azure AD 后,可以安装 ADAL 并编写标识相关的代码。Now that you have an app in Azure AD, you can install ADAL and write your identity-related code. 若要允许 ADAL 与 Azure AD 通信,请向其提供一些有关应用注册的信息。To enable ADAL to communicate with Azure AD, give it some information about the app registration.

  1. 使用包管理器控制台将 ADAL 添加到 DirectorySearcher 项目。Add ADAL to the DirectorySearcher project by using the Package Manager Console.

    PM> Install-Package Microsoft.IdentityModel.Clients.ActiveDirectory -ProjectName DirectorySearcherLib
    
    PM> Install-Package Microsoft.IdentityModel.Clients.ActiveDirectory -ProjectName DirSearchClient-Android
    
    PM> Install-Package Microsoft.IdentityModel.Clients.ActiveDirectory -ProjectName DirSearchClient-Desktop
    
    PM> Install-Package Microsoft.IdentityModel.Clients.ActiveDirectory -ProjectName DirSearchClient-iOS
    
    PM> Install-Package Microsoft.IdentityModel.Clients.ActiveDirectory -ProjectName DirSearchClient-Universal
    

    注意每个项目中添加了两个库:ADAL 的 PCL 部分,和特定于平台的部分。Note that two library references are added to each project: the PCL portion of ADAL and a platform-specific portion.

  2. 在 DirectorySearcherLib 项目中,打开 DirectorySearcher.cs。In the DirectorySearcherLib project, open DirectorySearcher.cs.

  3. 将类成员值替换为在 Azure 门户中输入的值。Replace the class member values with the values that you entered in the Azure portal. 只要使用 ADAL,代码就会引用这些值。Your code refers to these values whenever it uses ADAL.

    • tenant 是 Azure AD 租户的域(例如 contoso.partner.onmschina.cn)。The tenant is the domain of your Azure AD tenant (for example, contoso.partner.onmschina.cn).
    • clientId 是从门户中复制的应用的客户端 ID。The clientId is the client ID of the app, which you copied from the portal.
    • returnUri 是在门户中输入的重定向 URI (例如 http://DirectorySearcher)。The returnUri is the redirect URI that you entered in the portal (for example, http://DirectorySearcher).

步骤 4:使用 ADAL 从 Azure AD 获取令牌Step 4: Use ADAL to get tokens from Azure AD

几乎所有的应用的身份验证逻辑都位于 DirectorySearcher.SearchByAlias(...)Almost all of the app's authentication logic lies in DirectorySearcher.SearchByAlias(...). 在特定于平台的项目中,所要做的一切就是将上下文参数传递到 DirectorySearcher PCL。All that's necessary in the platform-specific projects is to pass a contextual parameter to the DirectorySearcher PCL.

  1. 打开 DirectorySearcher.cs,并将一个新参数添加到 SearchByAlias(...) 方法。Open DirectorySearcher.cs, and then add a new parameter to the SearchByAlias(...) method. IPlatformParameters 是上下文参数,用于封装 ADAL 需要对其执行身份验证的特定于平台的对象。is the contextual parameter that encapsulates the platform-specific objects that ADAL needs to perform the authentication.

    public static async Task<List<User>> SearchByAlias(string alias, IPlatformParameters parent)
    {
    
  2. 初始化 AuthenticationContext,这是 ADAL 的主类。Initialize AuthenticationContext, which is the primary class of ADAL. 此操作将传递 ADAL 与 Azure AD 通信时所需的坐标。This action passes ADAL the coordinates it needs to communicate with Azure AD.

  3. 调用 AcquireTokenAsync(...),该类接受 IPlatformParameters 对象,并调用所需的身份验证流来向应用程序返回令牌。Call AcquireTokenAsync(...), which accepts the IPlatformParameters object and invokes the authentication flow that's necessary to return a token to the app.

    ...
        AuthenticationResult authResult = null;
        try
        {
            AuthenticationContext authContext = new AuthenticationContext(authority);
            authResult = await authContext.AcquireTokenAsync(graphResourceUri, clientId, returnUri, parent);
        }
        catch (Exception ee)
        {
            results.Add(new User { error = ee.Message });
            return results;
        }
    ...
    

    AcquireTokenAsync(...) 首先会尝试返回请求资源(在本例中为图形 API)的令牌,而不提示用户输入其凭据(通过缓存或刷新旧令牌)。first attempts to return a token for the requested resource (the Graph API in this case) without prompting users to enter their credentials (via caching or refreshing old tokens). 必要时,它会在获取请求的令牌之前,向用户显示 Azure AD 登录页。As necessary, it shows users the Azure AD sign-in page before acquiring the requested token.

  4. Authorization 标头中将访问令牌附加到图形 API 请求:Attach the access token to the Graph API request in the Authorization header:

    ...
        request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", authResult.AccessToken);
    ...
    

这就是需要针对 DirectorySearcher PCL 和应用的标识相关代码执行的所有操作。That's all for the DirectorySearcher PCL and the app's identity-related code. 余下的操作是在每个平台的视图中调用 SearchByAlias(...) 方法,并根据需要添加代码来正确处理 UI 生命周期。All that remains is to call the SearchByAlias(...) method in each platform's views and, where necessary, to add code for correctly handling the UI lifecycle.

AndroidAndroid

  1. 在 MainActivity.cs 中,在按钮单击处理程序中添加对 SearchByAlias(...) 的调用:In MainActivity.cs, add a call to SearchByAlias(...) in the button click handler:

    List<User> results = await DirectorySearcher.SearchByAlias(searchTermText.Text, new PlatformParameters(this));
    
  2. 重写 OnActivityResult 生命周期方法,将所有身份验证重定向转发回到相应的方法。Override the OnActivityResult lifecycle method to forward any authentication redirects back to the appropriate method. ADAL 在 Android 中为此提供了帮助器方法:ADAL provides a helper method for this in Android:

    ...
    protected override void OnActivityResult(int requestCode, Result resultCode, Intent data)
    {
        base.OnActivityResult(requestCode, resultCode, data);
        AuthenticationAgentContinuationHelper.SetAuthenticationAgentContinuationEventArgs(requestCode, resultCode, data);
    }
    ...
    

Windows 桌面Windows Desktop

在 MainWindow.xaml.cs 中,只需调用 SearchByAlias(...),并在桌面的 PlatformParameters 对象中传递 WindowInteropHelperIn MainWindow.xaml.cs, make a call to SearchByAlias(...) by passing a WindowInteropHelper in the desktop's PlatformParameters object:

List<User> results = await DirectorySearcher.SearchByAlias(
  SearchTermText.Text,
  new PlatformParameters(PromptBehavior.Auto, this.Handle));

iOSiOS

在 DirSearchClient_iOSViewController.cs 中,iOS PlatformParameters 对象将引用视图控制器:In DirSearchClient_iOSViewController.cs, the iOS PlatformParameters object takes a reference to the View Controller:

List<User> results = await DirectorySearcher.SearchByAlias(
  SearchTermText.Text,
  new PlatformParameters(PromptBehavior.Auto, this.Handle));

Windows UniversalWindows Universal

在 Windows Universal 中打开 MainPage.xaml.cs,并实现 Search 方法。In Windows Universal, open MainPage.xaml.cs, and then implement the Search method. 此方法根据需要使用共享项目中的帮助器方法来更新 UI。This method uses a helper method in a shared project to update UI as necessary.

...
List<User> results = await DirectorySearcherLib.DirectorySearcher.SearchByAlias(SearchTermText.Text, new PlatformParameters(PromptBehavior.Auto, false));
...

现已创建一个正常运行的 Xamarin 应用,它可以对用户进行身份验证,并使用 OAuth 2.0 在五个不同的平台上安全调用 Web API。You now have a working Xamarin app that can authenticate users and securely call web APIs by using OAuth 2.0 across five different platforms.

步骤 5:填充租户Step 5: Populate your tenant

如果尚未在租户中填充用户,现在便可执行此操作。If you haven’t already populated your tenant with users, now is the time to do so.

  1. 运行 DirectorySearcher 应用,并使用其中一个用户进行登录。Run your DirectorySearcher app, and then sign in with one of the users.
  2. 根据用户的 UPN 搜索其他用户。Search for other users based on their UPN.

后续步骤Next steps

使用 ADAL 可以方便地将常见标识功能合并到应用中。ADAL makes it easy to incorporate common identity features into the app. 它会负责所有的繁琐工作,例如缓存管理、OAuth 协议支持、向用户显示登录 UI,以及刷新过期令牌。It takes care of all the dirty work for you, such as cache management, OAuth protocol support, presenting the user with a login UI, and refreshing expired tokens. 只需知道一个 API 调用,即 authContext.AcquireToken*(…)You need to know only a single API call, authContext.AcquireToken*(…).