快速入门:从 iOS 或 macOS 应用将用户登录并调用 Microsoft Graph APIQuickstart: Sign in users and call the Microsoft Graph API from an iOS or macOS app

本快速入门包含一个代码示例,该示例演示了本机 iOS 或 macOS 应用程序如何使用 Microsoft 标识平台登录工作和学校帐户、获取访问令牌并调用 Microsoft Graph API。This quickstart contains a code sample that demonstrates how a native iOS or macOS application can use the Microsoft identity platform to sign in work and school accounts, get an access token, and call the Microsoft Graph API.

本快速入门适用于 iOS 和 macOS 应用。This quickstart applies to both iOS and macOS apps. 某些步骤只是 iOS 应用所需的。Some steps are needed only for iOS apps. 这些步骤会指出它们仅适用于 iOS。Those steps call out that they are only for iOS.

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

备注

先决条件Prerequisites

  • XCode 10+XCode 10+
  • iOS 10+iOS 10+
  • macOS 10.12+macOS 10.12+

注册并下载快速入门应用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 the code sample

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

若要注册应用,请执行以下操作:To register your app,

  1. 转到新的 Azure 门户 - 应用注册窗格。Go to the new Azure portal - App registrations pane.
  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. 导航到面向开发人员的 Microsoft 标识平台的应用注册页。Navigate to the Microsoft identity platform for developers App registrations page.
  2. 选择“新注册”。Select New registration.
  3. “注册应用程序”页出现后,请输入应用程序的注册信息:When the Register an application page appears, enter your application's registration information:
    • 在“名称”部分输入一个当应用用户登录应用或进行应用许可时会显示给应用用户的有意义的应用程序名称。In the Name section, enter a meaningful application name that will be displayed to users of the app when they sign in or consent to your app.
    • 跳过此页上的其他配置。Skip other configurations on this page.
    • 选择 RegisterSelect Register.
  4. 在“管理”部分选择 Authentication > Add Platform > iOSIn the Manage section, select Authentication > Add Platform > iOS.
    • 输入应用程序的捆绑包标识符。Enter the Bundle Identifier for your application. 捆绑标识符只是一个用于唯一标识应用程序的唯一字符串,例如 com.<yourname>.identitysample.MSALMacOSThe bundle identifier is just a unique string that uniquely identifies your application, for example com.<yourname>.identitysample.MSALMacOS. 记下所用的值。Make a note of the value you use.
    • 请注意,iOS 配置也适用于 macOS 应用程序。Note that the iOS configuration is also applicable to macOS applications.
  5. 选择 Configure 并保存“MSAL 配置”详细信息,供稍后在本快速入门中使用。Select Configure and save the MSAL Configuration details for later in this quickstart.

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

为使此快速入门中的代码示例正常运行,需要添加与身份验证代理兼容的重定向 URI。For the code sample for this quickstart to work, you need to add a redirect URI compatible with the Auth broker.

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

步骤 2:下载示例项目Step 2: Download the sample project

步骤 3:安装依赖项Step 3: Install dependencies

在终端窗口中导航到已下载代码示例所在的文件夹,然后运行 pod install 以安装最新的 MSAL 库。In a terminal window, navigate to the folder with the downloaded code sample and run pod install to install the latest MSAL library.

步骤 4:应用已配置并可以运行Step 4: 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

步骤 4:配置项目Step 4: Configure your project

如果选择了上面的“选项 1”,则可跳过这些步骤。If you selected Option 1 above, you can skip these steps.

  1. 解压缩 zip 文件并在 XCode 中打开该项目。Extract the zip file and open the project in XCode.

  2. 编辑 ViewController.swift 并将以“let kClientID”开头的行替换为以下代码片段。Edit ViewController.swift and replace the line starting with 'let kClientID' with the following code snippet. 记住将 kClientID 的值更新为客户端 ID,该 ID 是你在本快速入门的前面部分通过门户注册应用时保存的:Remember to update the value for kClientID with the clientID that you saved when you registered your app in the portal earlier in this quickstart:

    let kClientID = "Enter_the_Application_Id_Here"
    
  3. 如果为 Azure AD 国家云生成应用,请将以“let kGraphEndpoint”和“let kAuthority”开头的行替换为正确的终结点。If you're building an app for Azure AD national clouds, replace the line starting with 'let kGraphEndpoint' and 'let kAuthority' with correct endpoints. 若要进行全局访问,请使用默认值:For global access, use default values:

    let kGraphEndpoint = "https://microsoftgraph.chinacloudapi.cn/"
    let kAuthority = "https://login.partner.microsoftonline.cn/common"
    
  4. 此处阐述了其他终结点。Other endpoints are documented here. 例如,若要使用 Azure AD 德国云运行本快速入门,请使用以下代码:For example, to run the quickstart with Azure AD Germany, use following:

    let kGraphEndpoint = "https://graph.microsoft.de/"
    let kAuthority = "https://login.microsoftonline.de/common"
    
  5. 打开项目设置。Open the project settings. 在“标识”部分,输入以前在门户中输入的捆绑标识符In the Identity section, enter the Bundle Identifier that you entered into the portal.

  6. 右键单击“Info.plist”,然后选择“打开为” > “源代码”。Right-click Info.plist and select Open As > Source Code.

  7. 在 dict 根节点下,将 Enter_the_bundle_Id_Here 替换为你在门户中使用的捆绑 IDUnder the dict root node, replace Enter_the_bundle_Id_Here with the Bundle Id that you used in the portal.

    <key>CFBundleURLTypes</key>
    <array>
       <dict>
          <key>CFBundleURLSchemes</key>
          <array>
             <string>msauth.Enter_the_Bundle_Id_Here</string>
          </array>
       </dict>
    </array>
    
    
  8. 生成并运行应用!Build & run the app!

更多信息More Information

阅读以下各部分来详细了解本快速入门。Read these sections to learn more about this quickstart.

获取 MSALGet MSAL

MSAL (MSAL.framework) 是一个库,用于用户登录和请求令牌,此类令牌用于访问受 Microsoft 标识平台保护的 API。MSAL (MSAL.framework) is the library used to sign in users and request tokens used to access an API protected by Microsoft identity platform. 可以使用以下过程将 MSAL 添加到应用程序中:You can add MSAL to your application using the following process:

$ vi Podfile

将以下内容添加到此 podfile(包含项目的目标):Add the following to this podfile (with your project's target):

use_frameworks!

target 'MSALiOS' do
   pod 'MSAL'
end

运行 CocoaPods 安装命令:Run CocoaPods installation command:

pod install

初始化 MSALInitialize MSAL

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

import MSAL

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

let authority = try MSALAADAuthority(url: URL(string: kAuthority)!)

let msalConfiguration = MSALPublicClientApplicationConfig(clientId: kClientID, redirectUri: nil, authority: authority)
self.applicationContext = try MSALPublicClientApplication(configuration: msalConfiguration)
其中:Where: 说明Description
clientId portal.azure.cn 中注册的应用程序的应用程序 IDThe Application ID from the application registered in portal.azure.cn
authority Microsoft 标识平台终结点。The Microsoft identity platform endpoint. 在大多数情况下,这将是 https://login.partner.microsoftonline.cn/commonIn most of cases this will be https://login.partner.microsoftonline.cn/common
redirectUri 应用程序的重定向 URI。The redirect URI of the application. 可以传递“nil”以使用默认值,也可以使用自定义重定向 URI。You can pass 'nil' to use the default value, or your custom redirect URI.

(仅适用于 iOS)其他应用要求For iOS only, additional app requirements

应用还必须在 AppDelegate 中有以下内容。Your app must also have the following in your AppDelegate. 这样就可以在你进行身份验证时让 MSAL SDK 处理来自身份验证代理应用的令牌响应。This lets MSAL SDK handle token response from the Auth broker app when you do authentication.

func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey : Any] = [:]) -> Bool {

       return MSALPublicClientApplication.handleMSALResponse(url, sourceApplication: options[UIApplication.OpenURLOptionsKey.sourceApplication] as? String)
   }

备注

在 iOS 13+ 上,如果采用 UISceneDelegate 而不是 UIApplicationDelegate,请改将此代码置于 scene:openURLContexts: 回调中(请参阅 Apple 的文档)。On iOS 13+, if you adopt UISceneDelegate instead of UIApplicationDelegate, place this code into the scene:openURLContexts: callback instead (See Apple's documentation). 如果支持兼容旧版 iOS 的 UISceneDelegate 和 UIApplicationDelegate,则需将 MSAL 回调置于两个位置。If you support both UISceneDelegate and UIApplicationDelegate for compatibility with older iOS, MSAL callback needs to be placed into both places.

func scene(_ scene: UIScene, openURLContexts URLContexts: Set<UIOpenURLContext>) {

       guard let urlContext = URLContexts.first else {
           return
       }

       let url = urlContext.url
       let sourceApp = urlContext.options.sourceApplication

       MSALPublicClientApplication.handleMSALResponse(url, sourceApplication: sourceApp)
   }

最后,应用必须在 Info.plist 中有一个与 CFBundleURLTypes 一起的 LSApplicationQueriesSchemes 条目。Finally, your app must have an LSApplicationQueriesSchemes entry in your Info.plist alongside the CFBundleURLTypes. 示例包含此条目。The sample comes with this included.

<key>LSApplicationQueriesSchemes</key>
<array>
   <string>msauthv2</string>
   <string>msauthv3</string>
</array>

登录用户与请求令牌Sign in users & request tokens

MSAL 有两种用来获取令牌的方法:acquireTokenacquireTokenSilentMSAL has two methods used to acquire tokens: acquireToken and acquireTokenSilent.

acquireToken:以交互方式获取令牌acquireToken: Get a token interactively

有些情况下,需要用户与 Microsoft 标识平台交互。Some situations require users to interact with Microsoft identity platform. 在这些情况下,最终用户可能需要选择其帐户、输入其凭据,或者同意应用的权限。In these cases, the end user may be required to select their account, enter their credentials, or consent to your app's permissions. 例如,For example,

  • 用户首次登录应用程序The first time users sign in to the application
  • 用户在重置其密码时需输入其凭据。If a user resets their password, they'll need to enter their credentials
  • 应用程序首次请求访问资源时When your application is requesting access to a resource for the first time
  • 需要 MFA 或其他条件访问策略时When MFA or other Conditional Access policies are required
let parameters = MSALInteractiveTokenParameters(scopes: kScopes, webviewParameters: self.webViewParamaters!)
self.applicationContext!.acquireToken(with: parameters) { (result, error) in /* Add your handling logic */}
其中:Where: 说明Description
scopes 包含所请求的范围(即针对 Microsoft Graph 的 ["https://microsoftgraph.chinacloudapi.cn/user.read"] 或针对自定义 Web API (api://<Application ID>/access_as_user) 的 [ "<Application ID URL>/scope" ]Contains the scopes being requested (that is, ["https://microsoftgraph.chinacloudapi.cn/user.read"] for Microsoft Graph or [ "<Application ID URL>/scope" ] for custom web APIs (api://<Application ID>/access_as_user)

acquireTokenSilent:以无提示方式获取访问令牌acquireTokenSilent: Get an access token silently

应用不应该在用户每次请求令牌时都要求他们登录。Apps shouldn't require their users to sign in every time they request a token. 如果用户已登录,则此方法允许应用以静默方式请求令牌。If the user has already signed in, this method allows apps to request tokens silently.

self.applicationContext!.getCurrentAccount(with: nil) { (currentAccount, previousAccount, error) in

   guard let account = currentAccount else {
      return
   }

   let silentParams = MSALSilentTokenParameters(scopes: self.kScopes, account: account)
   self.applicationContext!.acquireTokenSilent(with: silentParams) { (result, error) in /* Add your handling logic */}
}
其中:Where: 说明Description
scopes 包含所请求的范围(即针对 Microsoft Graph 的 ["https://microsoftgraph.chinacloudapi.cn/user.read"] 或针对自定义 Web API (api://<Application ID>/access_as_user) 的 [ "<Application ID URL>/scope" ]Contains the scopes being requested (that is, ["https://microsoftgraph.chinacloudapi.cn/user.read"] for Microsoft Graph or [ "<Application ID URL>/scope" ] for custom web APIs (api://<Application ID>/access_as_user)
account 请求令牌时对应的帐户。The account a token is being requested for. 本快速入门介绍单帐户应用程序。This quickstart is about a single account application. 如果要构建多帐户应用,则需要定义相关逻辑,以使用 accountsFromDeviceForParameters:completionBlock: 并传递正确的 accountIdentifier 来标识用于令牌请求的帐户If you want to build a multi-account app you'll need to define logic to identify which account to use for token requests using accountsFromDeviceForParameters:completionBlock: and passing correct accountIdentifier

后续步骤Next steps

试用 iOS 和 macOS 教程,了解有关如何构建应用程序的完整分步指南,包括本快速入门的完整说明。Try out the tutorial for iOS and macOS for a complete step-by-step guide on building applications, including a complete explanation of this quickstart.

了解如何创建本快速入门中使用的应用程序Learn how to create the application used in this quickstart

帮助和支持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.