向 Xamarin.Android 应用添加身份验证Add authentication to your Xamarin.Android app


Visual Studio App Center 支持以移动应用开发为中心的端到端集成服务。Visual Studio App Center supports end to end 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. 开发人员还可以利用“身份验证” 对其用户进行身份验证,并使用“数据” 服务在云中保留和同步应用数据。Developers can also leverage Auth to authenticate their users and Data service to persist and sync app data in the cloud.

如果希望将云服务集成到移动应用程序中,请立即注册到 App Center 中。If you are looking to integrate cloud services in your mobile application, sign up with App Center today.


本主题演示如何从客户端应用程序对移动应用的用户进行身份验证。This topic shows you how to authenticate users of a Mobile App from your client application. 在本教程中,使用 Azure 移动应用支持的标识提供者向快速入门项目添加身份验证。In this tutorial, you add authentication to the quickstart project using an identity provider that is supported by Azure Mobile Apps. 在移动应用中成功进行身份验证和授权后,显示用户 ID 值。After being successfully authenticated and authorized in the Mobile App, the user ID value is displayed.

本教程基于移动应用快速入门。This tutorial is based on the Mobile App quickstart. 还必须先完成教程 创建 Xamarin.Android 应用You must also first complete the tutorial Create a Xamarin.Android 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.

    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. 发生此异常的原因是应用尝试以未经身份验证的用户身份访问移动应用后端。This 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

已更新应用,在显示数据之前要求用户点击“登录” 按钮进行身份验证。The app is updated to require users to tap the Sign in button and authenticate before data is displayed.

  1. 将以下代码添加到 TodoActivity 类:Add the following code to the TodoActivity class:

    // Define an authenticated user.
    private MobileServiceUser user;
    private async Task<bool> Authenticate()
            var success = false;
                // Sign in with MicrosoftAccount login using a server-managed flow.
                user = await client.LoginAsync(this,
                        MobileServiceAuthenticationProvider.MicrosoftAccount, "{url_scheme_of_your_app}");
                CreateAndShowDialog(string.Format("you are now logged in - {0}",
                    user.UserId), "Logged in!");
                success = true;
            catch (Exception ex)
                CreateAndShowDialog(ex, "Authentication failed");
            return success;
    public async void LoginUser(View view)
        // Load data only after authentication succeeds.
        if (await Authenticate())
            //Hide the button after authentication succeeds.
            FindViewById<Button>(Resource.Id.buttonLoginUser).Visibility = ViewStates.Gone;
            // Load the data.

    此代码创建一个新方法(用于对用户进行身份验证)和新“登录” 按钮的方法处理程序。This creates a new method to authenticate a user and a method handler for a new Sign in button. 上面示例代码中的用户使用 MicrosoftAccount 登录进行身份验证。The user in the example code above is authenticated by using a MicrosoftAccount login. 对话框用于在进行身份验证后显示用户 ID。A dialog is used to display the user ID once authenticated.


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

  2. OnCreate 方法中,删除或注释掉以下代码行:In the OnCreate method, delete or comment-out the following line of code:

    OnRefreshItemsSelected ();
  3. 在 Activity_To_Do.axml 文件中,在现有 AddItem 按钮之前添加以下 LoginUser 按钮定义:In the Activity_To_Do.axml file, add the following LoginUser button definition before the existing AddItem button:

        android:text="@string/login_button_text" />
  4. 将以下元素添加到 Strings.xml 资源文件:Add the following element to the Strings.xml resources file:

    <string name="login_button_text">Sign in</string>
  5. 打开 AndroidManifest.xml 文件,并在 <application> XML 元素中添加以下代码:Open the AndroidManifest.xml file, add the following code inside <application> XML element:

     <activity android:name="com.microsoft.windowsazure.mobileservices.authentication.RedirectUrlActivity" android:launchMode="singleTop" android:noHistory="true">
         <action android:name="android.intent.action.VIEW" />
         <category android:name="android.intent.category.DEFAULT" />
         <category android:name="android.intent.category.BROWSABLE" />
         <data android:scheme="{url_scheme_of_your_app}" android:host="easyauth.callback" />
  6. 在 Visual Studio 或 Xamarin Studio 中,运行设备或模拟器中的客户端项目,并使用所选的标识提供者登录。In Visual Studio or Xamarin Studio, run the client project on a device or emulator and sign in with your chosen identity provider. 成功登录后,应用会显示登录 ID 和待办事项列表,用户可以对数据进行更新。When you are successfully logged-in, the app will display your login ID and the list of todo items, and you can make updates to the data.


应用程序崩溃并显示 Java.Lang.NoSuchMethodError: No static method startActivityThe application crashed with Java.Lang.NoSuchMethodError: No static method startActivity

在某些情况下,支持包中的冲突在 Visual Studio 中仅显示为警告,但应用程序在运行时会崩溃并显示此异常。In some cases, conflicts in the support packages displayed as just a warning in the Visual studio, but the application crashes with this exception at runtime. 在这种情况下,你需要确保在项目中引用的所有支持包都具有相同的版本。In this case you need to make sure that all the support packages referenced in your project have the same version. 对于 Android 平台,Azure 移动应用 NuGet 包具有 Xamarin.Android.Support.CustomTabs 依赖项,因此,如果你的项目使用较新的支持包,则你需要直接安装具有所需版本的此包以避免冲突。The Azure Mobile Apps NuGet package has Xamarin.Android.Support.CustomTabs dependency for Android platform, so if your project uses newer support packages you need to install this package with required version directly to avoid conflicts.