Add authentication to your iOS app(将身份验证添加到 iOS 应用)Add authentication to your iOS app

Note

Visual Studio App Center 正在投资于对移动应用开发至关重要的新集成服务。Visual Studio App Center is investing in new and integrated services central to mobile app development. 开发人员可以使用生成测试分发服务来设置持续集成和交付管道。Developers can use Build, Test and Distribute services to set up Continuous Integration and Delivery pipeline. 部署应用后,开发人员可以使用分析诊断服务监视其应用的状态和使用情况,并使用推送服务与用户互动。Once the app is deployed, developers can monitor the status and usage of their app using the Analytics and Diagnostics services, and engage with users using the Push service. 开发人员还可以利用 Auth 对用户进行身份验证,利用数据服务在云中持久保存和同步应用数据。Developers can also leverage Auth to authenticate their users and Data service to persist and sync app data in the cloud. 立即查看 App CenterCheck out App Center today.

本教程介绍如何使用支持的标识提供者向 iOS 快速入门 项目添加身份验证。In this tutorial, you add authentication to the iOS quick start project using a supported identity provider. 本教程基于 iOS 快速入门 教程,必须先完成该教程。This tutorial is based on the iOS quick start tutorial, which you must complete first.

注册应用以进行身份验证并配置应用服务Register your app for authentication and configure the App Service

首先,需要在标识提供者站点上注册应用,然后在移动应用后端设置提供者生成的凭据。First, you need to register your app at an identity provider's site, and then you will set the provider-generated credentials in the Mobile Apps back end.

  1. 请按照以下提供者特定的说明来配置首选标识提供者:Configure your preferred identity provider by following the provider-specific instructions:

  2. 为要在应用中支持的各提供者重复上述步骤。Repeat the previous steps for each provider you want to support in your app.

将应用添加到允许的外部重定向 URLAdd your app to the Allowed External Redirect URLs

安全身份验证要求为应用定义新的 URL 方案。Secure authentication requires that you define a new URL scheme for your app. 此方案允许在完成身份验证过程后,身份验证系统重定向到应用。This allows the authentication system to redirect back to your app once the authentication process is complete. 在本教程中,我们自始至终使用 URL 方案 appnameIn this tutorial, we use the URL scheme appname throughout. 但是,可以使用任何你所选的 URL 方案。However, you can use any URL scheme you choose. 该方案是移动应用的唯一方案。It should be unique to your mobile application. 在服务器端启用重定向:To enable the redirection on th server side:

  1. 在 [Azure 门户]中,选择应用服务。In the [Azure portal], select your App Service.

  2. 单击“身份验证/授权” 菜单选项。Click the Authentication / Authorization menu option.

  3. 在“验证提供程序” 部分下,单击“Azure Active Directory” 。Click Azure Active Directory under the Authentication Providers section.

  4. 将“管理模式” 设置为“高级” 。Set the Management mode to Advanced.

  5. 在“允许的外部重定向 URL” 中,输入 appname://easyauth.callbackIn the Allowed External Redirect URLs, enter appname://easyauth.callback. 此字符串中的 appname 是移动应用程序的 URL 方案。The appname in this string is the URL Scheme for your mobile application. 它应该遵循协议的正常 URL 规范(仅使用字母和数字,并以字母开头)。It should follow normal URL specification for a protocol (use letters and numbers only, and start with a letter). 应记下此字符串,因为在一些地方需要使用此 URL 方案调整移动应用代码。You should make a note of the string that you choose as you will need to adjust your mobile application code with the URL Scheme in several places.

  6. 单击 “确定”Click OK.

  7. 单击“保存” 。Click Save.

将权限限制给已经过身份验证的用户Restrict permissions to authenticated users

默认情况下,可匿名调用移动应用后端中的 API。By default, APIs in a Mobile Apps back end can be invoked anonymously. 接下来,需限制为仅可访问已验证的客户端。Next, you need to restrict access to only authenticated clients.

  • Node.js 后端(通过 Azure 门户)Node.js back end (via the Azure portal) :

    在移动应用设置中,单击“简易表” 并选择相应的表。In your Mobile Apps settings, click Easy Tables and select your table. 单击“更改权限” ,为所有权限选择“仅限已验证的访问” ,并单击“保存” 。Click Change permissions, select Authenticated access only for all permissions, and then click Save.

  • .NET 后端 (C#) :.NET back end (C#):

    在服务器项目中,导航到“控制器” > “TodoItemController.cs”。 In the server project, navigate to Controllers > TodoItemController.cs. [Authorize] 属性添加到“TodoItemController”类,如下所示。 Add the [Authorize] attribute to the TodoItemController class, as follows. 若要限制为仅可访问特定方法,还可只向这些方法应用此属性(而非类)。To restrict access only to specific methods, you can also apply this attribute just to those methods instead of the class. 重新发布服务器项目。Republish the server project.

    [Authorize]
    public class TodoItemController : TableController<TodoItem>
    
  • Node.js 后端(通过 Node.js 代码)Node.js backend (via Node.js code) :

    若要访问表时需验证身份,请向 Node.js 服务器脚本添加以下行:To require authentication for table access, add the following line to the Node.js server script:

    table.access = 'authenticated';
    

    有关更多详细信息,请参阅如何:要求在访问表时进行身份验证For more details, see How to: Require authentication for access to tables. 若要了解如何从站点下载快速入门代码项目,请参阅如何:使用 Git 下载 Node.js 后端快速入门代码项目To learn how to download the quickstart code project from your site, see How to: Download the Node.js backend quickstart code project using Git.

在 Xcode 中,按“运行” 启动应用。In Xcode, press Run to start the app. 将引发一个异常,因为应用尝试以未经身份验证的用户身份访问后端,但 TodoItem 表现在要求身份验证。An exception is raised because the app attempts to access the backend as an unauthenticated user, but the TodoItem table now requires authentication.

向应用程序添加身份验证Add authentication to app

Objective-CObjective-C:

  1. 在 Mac 的 Xcode 中打开 QSTodoListViewController.m 并添加以下方法:On your Mac, open QSTodoListViewController.m in Xcode and add the following method:

    - (void)loginAndGetData
    {
        QSAppDelegate *appDelegate = (QSAppDelegate *)[UIApplication sharedApplication].delegate;
        appDelegate.qsTodoService = self.todoService;
    
        [self.todoService.client loginWithProvider:@"baidu" urlScheme:@"appname" controller:self animated:YES completion:^(MSUser * _Nullable user, NSError * _Nullable error) {
            if (error) {
                NSLog(@"Login failed with error: %@, %@", error, [error userInfo]);
            }
            else {
                self.todoService.client.currentUser = user;
                NSLog(@"User logged in: %@", user.userId);
    
                [self refresh];
            }
        }];
    }
    

    使用 microsoftaccount 或 windowsazureactivedirectory 作为标识提供者。Use microsoftaccount or windowsazureactivedirectory as your identity provider.

    urlScheme 替换为应用的唯一名称。Replace the urlScheme with a unique name for your application. urlScheme 应与在 Azure 门户中的“允许的外部重定向 URL”字段中指定的 URL 方案协议相同 。The urlScheme should be the same as the URL Scheme protocol that you specified in the Allowed External Redirect URLs field in the Azure portal. 身份验证回调使用 urlScheme 在完成身份验证请求之后切换回到应用。The urlScheme is used by the authentication callback to switch back to your application after the authentication request is complete.

  2. 将 QSTodoListViewController.m 中 viewDidLoad[self refresh] 替换为以下代码:Replace [self refresh] in viewDidLoad in QSTodoListViewController.m with the following code:

    [self loginAndGetData];
    
  3. 打开 QSAppDelegate.h 文件,并添加以下代码:Open the QSAppDelegate.h file and add the following code:

    #import "QSTodoService.h"
    
    @property (strong, nonatomic) QSTodoService *qsTodoService;
    
  4. 打开 QSAppDelegate.m 文件,并添加以下代码:Open the QSAppDelegate.m file and add the following code:

    - (BOOL)application:(UIApplication *)application openURL:(NSURL *)url options:(NSDictionary<UIApplicationOpenURLOptionsKey,id> *)options
    {
        if ([[url.scheme lowercaseString] isEqualToString:@"appname"]) {
            // Resume login flow
            return [self.qsTodoService.client resumeWithURL:url];
        }
        else {
            return NO;
        }
    }
    

    在行读取 #pragma mark - Core Data stack之前直接添加此代码。Add this code directly before the line reading #pragma mark - Core Data stack. 将 appname 替换为步骤 1 中使用的 urlScheme 值。Replace the appname with the urlScheme value that you used in step 1.

  5. 打开 AppName-Info.plist 文件(将 AppName 替换为应用的名称),并添加以下代码:Open the AppName-Info.plist file (replacing AppName with the name of your app), and add the following code:

    <key>CFBundleURLTypes</key>
    <array>
        <dict>
            <key>CFBundleURLName</key>
            <string>com.microsoft.azure.zumo</string>
            <key>CFBundleURLSchemes</key>
            <array>
                <string>appname</string>
            </array>
        </dict>
    </array>
    

    此代码应放置在 <dict> 元素内部。This code should be placed inside the <dict> element. 将 appname 字符串(位于 CFBundleURLSchemes 的数组内)替换为步骤 1 中所选的应用名称。Replace the appname string (within the array for CFBundleURLSchemes) with the app name you chose in step 1. 还可在 plist 编辑器中做这些更改 - 单击 XCode 中的 AppName-Info.plist 文件,打开 plist 编辑器。You can also make these changes in the plist editor - click on the AppName-Info.plist file in XCode to open the plist editor.

    将 CFBundleURLName 的 com.microsoft.azure.zumo 字符串替换为 Apple 捆绑包标识符。Replace the com.microsoft.azure.zumo string for CFBundleURLName with your Apple bundle identifier.

  6. 按“运行” 启动应用,然后登录。Press Run to start the app, and then log in. 登录后,应可以查看 Todo 列表并进行更新。When you are logged in, you should be able to view the Todo list and make updates.

SwiftSwift:

  1. 在 Mac 的 Xcode 中打开 ToDoTableViewController.swift 并添加以下方法:On your Mac, open ToDoTableViewController.swift in Xcode and add the following method:

    func loginAndGetData() {
    
        guard let client = self.table?.client, client.currentUser == nil else {
            return
        }
    
        let appDelegate = UIApplication.shared.delegate as! AppDelegate
        appDelegate.todoTableViewController = self
    
        let loginBlock: MSClientLoginBlock = {(user, error) -> Void in
            if (error != nil) {
                print("Error: \(error?.localizedDescription)")
            }
            else {
                client.currentUser = user
                print("User logged in: \(user?.userId)")
            }
        }
    
        client.login(withProvider:"baidu", urlScheme: "appname", controller: self, animated: true, completion: loginBlock)
    
    }
    

    使用 microsoftaccount 或 windowsazureactivedirectory 作为标识提供者。Use microsoftaccount or windowsazureactivedirectory as your identity provider.

    urlScheme 替换为应用的唯一名称。Replace the urlScheme with a unique name for your application. urlScheme 应与在 Azure 门户中的“允许的外部重定向 URL”字段中指定的 URL 方案协议相同 。The urlScheme should be the same as the URL Scheme protocol that you specified in the Allowed External Redirect URLs field in the Azure portal. 身份验证回调使用 urlScheme 在完成身份验证请求之后切换回到应用。The urlScheme is used by the authentication callback to switch back to your application after the authentication request is complete.

  2. 删除 ToDoTableViewController.swift 中 viewDidLoad() 末尾的 self.refreshControl?.beginRefreshing()self.onRefresh(self.refreshControl) 行。Remove the lines self.refreshControl?.beginRefreshing() and self.onRefresh(self.refreshControl) at the end of viewDidLoad() in ToDoTableViewController.swift. 在其位置上添加对 loginAndGetData() 的调用:Add a call to loginAndGetData() in their place:

    loginAndGetData()
    
  3. 打开 AppDelegate.swift 文件,将以下行添加到 AppDelegate 类:Open the AppDelegate.swift file and add the following line to the AppDelegate class:

    var todoTableViewController: ToDoTableViewController?
    
    func application(_ application: UIApplication, openURL url: NSURL, options: [UIApplicationOpenURLOptionsKey : Any] = [:]) -> Bool {
        if url.scheme?.lowercased() == "appname" {
            return (todoTableViewController!.table?.client.resume(with: url as URL))!
        }
        else {
            return false
        }
    }
    

    将 appname 替换为步骤 1 中使用的 urlScheme 值。Replace the appname with the urlScheme value that you used in step 1.

  4. 打开 AppName-Info.plist 文件(将 AppName 替换为应用的名称),并添加以下代码:Open the AppName-Info.plist file (replacing AppName with the name of your app), and add the following code:

    <key>CFBundleURLTypes</key>
    <array>
        <dict>
            <key>CFBundleURLName</key>
            <string>com.microsoft.azure.zumo</string>
            <key>CFBundleURLSchemes</key>
            <array>
                <string>appname</string>
            </array>
        </dict>
    </array>
    

    此代码应放置在 <dict> 元素内部。This code should be placed inside the <dict> element. 将 appname 字符串(位于 CFBundleURLSchemes 的数组内)替换为步骤 1 中所选的应用名称。Replace the appname string (within the array for CFBundleURLSchemes) with the app name you chose in step 1. 还可在 plist 编辑器中做这些更改 - 单击 XCode 中的 AppName-Info.plist 文件,打开 plist 编辑器。You can also make these changes in the plist editor - click on the AppName-Info.plist file in XCode to open the plist editor.

    将 CFBundleURLName 的 com.microsoft.azure.zumo 字符串替换为 Apple 捆绑包标识符。Replace the com.microsoft.azure.zumo string for CFBundleURLName with your Apple bundle identifier.

  5. 按“运行” 启动应用,然后登录。Press Run to start the app, and then log in. 登录后,应可以查看 Todo 列表并进行更新。When you are logged in, you should be able to view the Todo list and make updates.

应用服务身份验证使用 Apple 应用间通信。App Service Authentication uses Apples Inter-App Communication. 有关此主题的更多详细信息,请参阅 [Apple 文档][2]For more details on this subject, refer to the [Apple Documentation][2]

[2]: https://developer.apple.com/library/content/documentation/iPhone/Conceptual/iPhoneOSProgrammingGuide/Inter-AppCommunication/Inter-AppCommunication.html [Azure 门户]: https://portal.azure.cn