快速入门:从 iOS 或 macOS 应用将用户登录并调用 Microsoft Graph APIQuickstart: Sign in users and call the Microsoft Graph API from an iOS or macOS app
在本快速入门中,你将下载并运行一个代码示例,该示例演示本机 iOS 或 macOS 应用程序如何让用户登录并获取访问令牌来调用 Microsoft Graph API。In this quickstart, you download and run a code sample that demonstrates how a native iOS or macOS application can sign in users and get an access token to call the Microsoft Graph API.
本快速入门适用于 iOS 和 macOS 应用。The quickstart applies to both iOS and macOS apps. 某些步骤仅为 iOS 应用所需,并将如下所示进行说明。Some steps are needed only for iOS apps and will be indicated as such.
先决条件Prerequisites
- 具有活动订阅的 Azure 帐户。An Azure account with an active subscription. 创建帐户。Create an account.
- XCode 10+XCode 10+
- iOS 10+iOS 10+
- macOS 10.12+macOS 10.12+
示例工作原理How the sample works
注册并下载快速入门应用Register and download your quickstart app
可以使用两个选项来启动快速入门应用程序:You have two options to start your quickstart application:
- [快速]选项 1:注册并自动配置应用,然后下载代码示例[Express] Option 1: Register and auto configure your app and then download your code sample
- [手动]选项 2:注册并手动配置应用程序和代码示例[Manual] Option 2: Register and manually configure your application and code sample
选项 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,
- 转到新的 Azure 门户 - 应用注册窗格。Go to the new Azure portal - App registrations pane.
- 输入应用程序的名称并选择“注册”。Enter a name for your application and select Register.
- 遵照说明下载内容,并只需单击一下自动配置新应用程序。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:
- 登录到 Azure 门户。Sign in to the Azure portal.
- 如果有权访问多个租户,请使用顶部菜单中的“目录 + 订阅”筛选器
,选择要在其中注册应用程序的租户。
- 搜索并选择“Azure Active Directory” 。Search for and select Azure Active Directory.
- 在“管理”下,选择“应用注册” > “新建注册” 。Under Manage, select App registrations > New registration.
- 输入应用程序的 名称。Enter a Name for your application. 应用的用户可能会看到此名称,你稍后可对其进行更改。Users of your app might see this name, and you can change it later.
- 选择“注册” 。Select Register.
- 在“管理”下,选择“身份验证” > “添加平台” > “iOS” 。Under Manage, select Authentication > Add Platform > iOS.
- 输入应用程序的捆绑包标识符。Enter the Bundle Identifier for your application. 捆绑标识符是用于唯一标识应用程序的唯一字符串,例如
com.<yourname>.identitysample.MSALMacOS
。The bundle identifier is a unique string that uniquely identifies your application, for examplecom.<yourname>.identitysample.MSALMacOS
. 记下所用的值。Make a note of the value you use. 请注意,iOS 配置也适用于 macOS 应用程序。Note that the iOS configuration is also applicable to macOS applications. - 选择“配置”并保存“MSAL 配置”详细信息,供稍后在本快速入门中使用 。Select Configure and save the MSAL Configuration details for later in this quickstart.
- 选择“完成”。Select Done.
步骤 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.
应用程序已使用这些属性进行了配置
Your application is configured with these attributes
步骤 2:下载示例项目Step 2: Download the sample project
步骤 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.
解压缩 zip 文件并在 XCode 中打开该项目。Extract the zip file and open the project in XCode.
编辑 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 forkClientID
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"
如果为 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"
此处阐述了其他终结点。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"
打开项目设置。Open the project settings. 在“标识”部分,输入以前在门户中输入的 捆绑标识符。In the Identity section, enter the Bundle Identifier that you entered into the portal.
右键单击“Info.plist”,然后选择“打开为” > “源代码”。Right-click Info.plist and select Open As > Source Code.
在 dict 根节点下,将
Enter_the_bundle_Id_Here
替换为你在门户中使用的“捆绑 ID”。Under the dict root node, replaceEnter_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>
生成并运行应用!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/common
In most of cases this will behttps://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 有两种用来获取令牌的方法:acquireToken
和 acquireTokenSilent
。MSAL 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 usingaccountsFromDeviceForParameters:completionBlock:
and passing correctaccountIdentifier
帮助和支持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
继续学习分步教程,在该教程中,你将生成一个从 Microsoft 标识平台获取访问令牌并使用它来调用 Microsoft Graph API 的 iOS 或 macOS 应用。Move on to the step-by-step tutorial in which you build an iOS or macOS app that gets an access token from the Microsoft identity platform and uses it to call the Microsoft Graph API.