将身份验证添加到 Apache Cordova 应用Add authentication to your Apache Cordova 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.

摘要Summary

本教程介绍如何使用支持的标识提供者将身份验证添加到 Apache Cordova 上的待办事项列表快速入门项目。In this tutorial, you add authentication to the todolist quickstart project on Apache Cordova using a supported identity provider. 本教程基于 Get started with Mobile Apps (移动应用入门)教程,必须先完成该教程。This tutorial is based on the Get started with Mobile Apps 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.

将权限限制给已经过身份验证的用户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.

现在,可以验证是否已禁用对后端的匿名访问。Now, you can verify that anonymous access to your backend has been disabled. 在 Visual Studio 中:In Visual Studio:

  • 打开你在完成 Get started with Mobile Apps教程后创建的项目。Open the project that you created when you completed the tutorial Get started with Mobile Apps.
  • Android 模拟器中运行应用程序。Run your application in the Android Emulator.
  • 验证应用启动后显示“意外的连接失败”。Verify that an Unexpected Connection Failure is shown after the app starts.

接下来,请更新应用,以便在从移动应用后端请求资源之前对用户进行身份验证。Next, update the app to authenticate users before requesting resources from the Mobile App backend.

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

  1. Visual Studio 中打开项目,然后打开 www/index.html 文件进行编辑。Open your project in Visual Studio, then open the www/index.html file for editing.

  2. 找到 head 节中的 Content-Security-Policy 元标记。Locate the Content-Security-Policy meta tag in the head section. 将 OAuth 主机添加到允许的源列表。Add the OAuth host to the list of allowed sources.

    提供程序Provider SDK 提供程序名称SDK Provider Name OAuth 主机OAuth Host
    Azure Active DirectoryAzure Active Directory aadaad https://login.chinacloudapi.cn
    MicrosoftMicrosoft microsoftaccountmicrosoftaccount https://login.live.com

    下面显示了 Content-Security-Policy(针对 Azure Active Directory 实现)的示例:An example Content-Security-Policy (implemented for Azure Active Directory) is as follows:

    <meta http-equiv="Content-Security-Policy" content="default-src 'self'
        data: gap: https://login.chinacloudapi.cn https://yourapp.chinacloudsites.cn; style-src 'self'">
    

    https://login.chinacloudapi.cn 替换为上表中的 OAuth 主机。Replace https://login.chinacloudapi.cn with the OAuth host from the preceding table. 有关 content-security-policy 元标记的详细信息,请参阅 Content-Security-Policy 文档For more information about the content-security-policy meta tag, see the Content-Security-Policy documentation.

  3. 打开 www/js/index.js 文件进行编辑,找到 onDeviceReady() 方法,然后在客户端创建代码下添加以下代码:Open the www/js/index.js file for editing, locate the onDeviceReady() method, and under the client creation code add the following code:

    // Login to the service
    client.login('SDK_Provider_Name')
        .then(function () {
    
            // BEGINNING OF ORIGINAL CODE
    
            // Create a table reference
            todoItemTable = client.getTable('todoitem');
    
            // Refresh the todoItems
            refreshDisplay();
    
            // Wire up the UI Event Handler for the Add Item
            $('#add-item').submit(addItemHandler);
            $('#refresh').on('click', refreshDisplay);
    
            // END OF ORIGINAL CODE
    
        }, handleError);
    

    此代码替换用于创建表引用和刷新 UI 的现有代码。This code replaces the existing code that creates the table reference and refreshes the UI.

    login() 方法开始对提供程序进行身份验证。The login() method starts authentication with the provider. login() 方法是返回 JavaScript Promise 的异步函数。The login() method is an async function that returns a JavaScript Promise. 初始化的剩余部分放置在 promise 响应中,因此在 login() 方法完成之前不会执行。The rest of the initialization is placed inside the promise response so that it is not executed until the login() method completes.

  4. 在刚刚添加的代码中,将 SDK_Provider_Name 替换为登录提供程序的名称。In the code that you just added, replace SDK_Provider_Name with the name of your login provider. 例如,对于 Azure Active Directory,请使用 client.login('aad')For example, for Azure Active Directory, use client.login('aad').

  5. 运行项目。Run your project. 项目完成初始化后,应用程序针对所选的身份验证提供程序显示 OAuth 登录页。When the project has finished initializing, your application shows the OAuth login page for the chosen authentication provider.

后续步骤Next Steps

了解如何使用 SDK。Learn how to use the SDKs.