向 Xamarin.iOS 应用添加身份验证Add authentication to your Xamarin.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.

概述Overview

本主题演示如何从客户端应用程序对应用服务移动应用的用户进行身份验证。This topic shows you how to authenticate users of an App Service Mobile App from your client application. 在本教程中,使用应用服务支持的标识提供者向 Xamarin.iOS 快速入门项目添加身份验证。In this tutorial, you add authentication to the Xamarin.iOS quickstart project using an identity provider that is supported by App Service. 移动应用成功进行身份验证和授权后,将显示用户 ID 值,该用户能够访问受限制的表数据。After being successfully authenticated and authorized by your Mobile App, the user ID value is displayed and you will be able to access restricted table data.

必须先完成教程 创建 Xamarin.iOS 应用You must first complete the tutorial Create a Xamarin.iOS app. 如果不使用下载的快速入门服务器项目,必须将身份验证扩展包添加到项目。If you do not use the downloaded quick start server project, you must add the authentication extension package to your project. 有关服务器扩展包的详细信息,请参阅使用适用于 Azure 移动应用的 .NET 后端服务器 SDKFor more information about server extension packages, see Work with the .NET backend server SDK for Azure Mobile Apps.

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

首先,需要在标识提供者站点上注册应用,然后在移动应用后端设置提供者生成的凭据。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 the server side:

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

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

  3. 在“允许的外部重定向 URL” 中,输入 url_scheme_of_your_app://easyauth.callbackIn the Allowed External Redirect URLs, enter url_scheme_of_your_app://easyauth.callback. 此字符串中的 url_scheme_of_your_app 是移动应用程序的 URL 方案。The url_scheme_of_your_app 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.

  4. 单击 “确定”Click OK.

  5. 单击“保存” 。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.

  • 在 Visual Studio 或 Xamarin Studio 中,运行设备或模拟器中的客户端项目。In Visual Studio or Xamarin Studio, run the client project on a device or emulator. 验证在应用启动后是否引发状态代码为 401(“未授权”)的未处理异常。Verify that an unhandled exception with a status code of 401 (Unauthorized) is raised after the app starts. 失败将记录到调试器的控制台中。The failure is logged to the console of the debugger. 因此,在 Visual Studio 中,应在输出窗口中看到失败。So in Visual Studio, you should see the failure in the output window.

    发生此未授权失败的原因是应用尝试以未经身份验证的用户身份访问移动应用后端。This unauthorized failure happens because the app attempts to access your Mobile App backend as an unauthenticated user. TodoItem 表现在要求身份验证。The TodoItem table now requires authentication.

接下来,更新客户端应用,以使用经过身份验证的用户从移动应用后端请求资源。Next, you will update the client app to request resources from the Mobile App backend with an authenticated user.

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

本部分介绍如何修改应用程序,以便在显示数据之前显示登录屏幕。In this section, you will modify the app to display a login screen before displaying data. 应用启动时,它不会连接到应用服务,并且不会显示任何数据。When the app starts, it will not connect to your App Service and will not display any data. 用户首次执行刷新笔势后,显示登录屏幕;成功登录后,显示 Todo 项列表。After the first time that the user performs the refresh gesture, the login screen will appear; after successful login the list of todo items will be displayed.

  1. 在客户端项目中,打开文件 QSTodoService.cs,向 QSTodoService 类添加以下 using 语句和带访问器的 MobileServiceUserIn the client project, open the file QSTodoService.cs and add the following using statement and MobileServiceUser with accessor to the QSTodoService class:

    using UIKit;
    
    // Logged in user
    private MobileServiceUser user;
    public MobileServiceUser User { get { return user; } }
    
  2. 使用以下定义向 QSTodoService 添加名为 Authenticate 的新方法:Add new method named Authenticate to QSTodoService with the following definition:

    public async Task Authenticate(UIViewController view)
    {
        try
        {
            AppDelegate.ResumeWithURL = url => url.Scheme == "{url_scheme_of_your_app}" && client.ResumeWithURL(url);
            user = await client.LoginAsync(view, MobileServiceAuthenticationProvider.MicrosoftAccout, "{url_scheme_of_your_app}");
        }
        catch (Exception ex)
        {
            Console.Error.WriteLine (@"ERROR - AUTHENTICATION FAILED {0}", ex.Message);
        }
    }
    

    Note

    如果使用的标识提供者不是 MicrosoftAccount,请将传递给上述 LoginAsync 的值更改为以下值:WindowsAzureActiveDirectoryIf you are using an identity provider other than a MicrosoftAccount, change the value passed to LoginAsync above to the following: WindowsAzureActiveDirectory.

  3. 打开 QSTodoListViewController.csOpen QSTodoListViewController.cs. 修改 ViewDidLoad 的方法定义,删除接近结尾处对 RefreshAsync() 的调用:Modify the method definition of ViewDidLoad removing the call to RefreshAsync() near the end:

    public override async void ViewDidLoad ()
    {
        base.ViewDidLoad ();
    
        todoService = QSTodoService.DefaultService;
        await todoService.InitializeStoreAsync();
    
        RefreshControl.ValueChanged += async (sender, e) => {
            await RefreshAsync();
        }
    
        // Comment out the call to RefreshAsync
        // await RefreshAsync();
    }
    
  4. 修改方法 RefreshAsync,以便在 User 属性为 null 时进行身份验证。Modify the method RefreshAsync to authenticate if the User property is null. 将以下代码添加到方法定义顶部:Add the following code at the top of the method definition:

    // start of RefreshAsync method
    if (todoService.User == null) {
        await QSTodoService.DefaultService.Authenticate(this);
        if (todoService.User == null) {
            Console.WriteLine("couldn't login!!");
            return;
        }
    }
    // rest of RefreshAsync method
    
  5. 打开 AppDelegate.cs,添加以下方法:Open AppDelegate.cs, add the following method:

    public static Func<NSUrl, bool> ResumeWithURL;
    
    public override bool OpenUrl(UIApplication app, NSUrl url, NSDictionary options)
    {
        return ResumeWithURL != null && ResumeWithURL(url);
    }
    
  6. 打开 Info.plist 文件,导航到“高级” 节中的“URL 类型” 。Open Info.plist file, navigate to URL Types in the Advanced section. 现在,配置 URL 类型的“标识符” 和“URL 方案” ,然后单击“添加 URL 类型” 。Now configure the Identifier and the URL Schemes of your URL Type and click Add URL Type. URL 方案应与 {url_scheme_of_your_app} 相同。URL Schemes should be the same as your {url_scheme_of_your_app}.

  7. 在已连接到 Mac 主机的 Visual Studio 中或在 Visual Studio for Mac 中,针对设备或模拟器运行客户端项目。In Visual Studio, connected to your Mac Host or Visual Studio for Mac, run the client project targeting a device or emulator. 验证应用程序是否未显示任何数据。Verify that the app displays no data.

    通过向下拉动项列表来执行刷新笔势,这会导致显示登录屏幕。Perform the refresh gesture by pulling down the list of items, which will cause the login screen to appear. 成功输入有效的凭据后,应用会显示待办事项列表,用户可以对数据进行更新。Once you have successfully entered valid credentials, the app will display the list of todo items, and you can make updates to the data.