概觀
本主題說明如何從用戶端應用程式驗證 App Service 行動應用程式的使用者。 在本教學課程中,您會使用App Service支援的識別提供者,將驗證新增至 Xamarin Forms 快速入門專案。 在行動裝置應用程式成功驗證和授權之後,會顯示使用者標識碼值,而且您將能夠存取受限制的數據表數據。
先決條件
如需本教學課程的最佳結果,建議您先完成 建立 Xamarin Forms 應用程式 教學課程。 完成本教學課程之後,您將會有一個多平臺 TodoList 應用程式的 Xamarin Forms 專案。
如果您未使用下載的快速入門伺服器專案,您必須將驗證延伸模組套件新增至您的專案。 如需伺服器擴充套件的詳細資訊,請參閱 使用適用於 Azure Mobile Apps 的 .NET 後端伺服器 SDK。
註冊您的應用程式以進行驗證並設定App Services
首先,您必須在身分提供者的網站註冊您的應用程式,然後在行動應用程式的後端設定提供者產生的認證。
按照提供商的特定指示來設定您的首選身分驗證提供者:
針對您想要在應用程式中支援的每個提供者重複上述步驟。
將您的應用程式新增至允許的外部重新導向URL
安全驗證需要您為應用程式定義新的 URL 配置。 這可讓驗證系統在驗證程式完成之後重新導向回您的應用程式。 在本教學課程中,我們會在整個過程中使用 URL scheme appname。 不過,您可以使用您選擇的任何 URL 配置。 它應該是您的行動應用程式所特有的。 若要在伺服器端開啟重新導向:
在 Azure 入口網站中,選取您的 App Service(應用服務)。
按一下 [驗證/授權] 選單選項。
在 [允許的外部重新導向 URL中,輸入
url_scheme_of_your_app://easyauth.callback。 此字串中的 url_scheme_of_your_app 是行動應用程式的URL配置。 它應該遵循通訊協定的一般 URL 規格(只使用字母和數位,並以字母開頭)。 您應該記下您選擇的字串,因為您需要在數個地方使用URL配置來調整行動應用程式程式代碼。按一下 [確定]。
點選 [儲存]。
限制已驗證用戶的許可權
根據預設,Mobile Apps 後端中的 API 可以匿名叫用。 接下來,您必須限制僅對已驗證用戶端的存取。
Node.js 後端 (透過 Azure 入口網站):
在Mobile Apps 設定中,按兩下 [[簡易數據表],然後選取您的數據表。 按一下 [變更許可權],針對所有許可權選取 [僅限已驗證存取 ],然後按一下 [儲存]。
.NET 後端 (C#):
在伺服器專案中,流覽至 Controllers>TodoItemController.cs。 將
[Authorize]屬性新增至 TodoItemController 類別,如下所示。 若要只限制對特定方法的存取,您也可以只將此屬性套用至那些方法,而不是類別。 重新發佈伺服器專案。[Authorize] public class TodoItemController : TableController<TodoItem>Node.js 後端(透過 Node.js 程式代碼):
若要要求驗證資料表存取,請將下列這一行新增至 Node.js 伺服器腳本:
table.access = 'authenticated';如需詳細資訊,請參閱 如何:要求驗證才能存取數據表。 若要瞭解如何從您的網站下載快速入門程式代碼專案,請參閱 如何:使用 Git下載 Node.js 後端快速入門程式代碼專案。
將驗證新增至可攜式類別庫
Mobile Apps 會在 MobileServiceClient 上使用 LoginAsync 擴充方法,以使用 App Service 驗證登入使用者。 此範例會使用伺服器管理的驗證流程,在應用程式中顯示提供者的登入介面。 如需詳細資訊,請參閱 伺服器管理的驗證。 若要在生產應用程式中提供更好的用戶體驗,您應該考慮改用 用戶端管理的驗證。
若要向 Xamarin Forms 專案進行驗證,請在應用程式的可攜式類別庫中定義 IAuthenticate 介面。 然後,將 [登入] 按鈕新增至可攜式類別庫中定義的使用者介面,您按兩下即可開始驗證。 成功驗證之後,數據會從行動應用程式後端載入。
針對應用程式所支援的每個平臺,實作 IAuthenticate 介面。
在 Visual Studio 或 Xamarin Studio 中,打開名稱包含 Portable 的可攜式類別庫專案中的 App.cs,然後新增下列
using語句:```csharp using System.Threading.Tasks; ```在 App.cs 中,在
IAuthenticate類別定義之前,立即新增下列App介面定義。```csharp public interface IAuthenticate { Task<bool> Authenticate(); } ```若要使用平臺特定實作初始化 介面,請將下列靜態成員新增至 App 類別。
```csharp public static IAuthenticate Authenticator { get; private set; } public static void Init(IAuthenticate authenticator) { Authenticator = authenticator; } ```從可攜式類別庫項目開啟 TodoList.xaml,在現有按鈕之後,於 buttonsPanel layout 元素中新增下列 Button 元素:
```xml <Button x:Name="loginButton" Text="Sign-in" MinimumHeightRequest="30" Clicked="loginButton_Clicked"/> ```這個按鈕會觸發行動應用程式後端的伺服器管理驗證。
從可攜式類別庫項目開啟TodoList.xaml.cs,然後將下列欄位新增至
TodoList類別:```csharp // Track whether the user has authenticated. bool authenticated = false; ```以下列程序代碼取代 OnAppearing 方法:
```csharp protected override async void OnAppearing() { base.OnAppearing(); // Refresh items only when authenticated. if (authenticated == true) { // Set syncItems to true in order to synchronize the data // on startup when running in offline mode. await RefreshItems(true, syncItems: false); // Hide the Sign-in button. this.loginButton.IsVisible = false; } } ```此程式碼確保只有在身份驗證完成後,才會從服務重新整理資料。
將 Clicked 事件的下列處理程式新增至 TodoList 類別:
```csharp async void loginButton_Clicked(object sender, EventArgs e) { if (App.Authenticator != null) authenticated = await App.Authenticator.Authenticate(); // Set syncItems to true to synchronize the data on startup when offline is enabled. if (authenticated == true) await RefreshItems(true, syncItems: false); } ```儲存您的變更並重建可攜式類別庫專案,確認沒有任何錯誤。
將驗證新增至 Android 應用程式
本節說明如何在Android應用程式專案中實作 IAuthenticate 介面。 如果您不支援 Android 裝置,請略過本節。
在 Visual Studio 或 Xamarin Studio 中,右鍵點擊 droid 專案,然後 設定為啟動專案。
按 F5 在除錯程式中啟動項目,然後確認在應用程式啟動時引發狀態代碼為 401(未經授權)的未處理例外狀況。 會產生 401 程式代碼,因為後端的存取僅限於授權的使用者。
在 Android 項目中開啟MainActivity.cs,並新增下列
using語句:```csharp using Microsoft.WindowsAzure.MobileServices; using System.Threading.Tasks; ```更新 MainActivity 類別,以實作 IAuthenticate 介面,如下所示:
```csharp public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsApplicationActivity, IAuthenticate ```更新 MainActivity 類別,新增 MobileServiceUser 欄位和 Authenticate 方法,這是 IAuthenticate 介面所需要的,如下所示:
```csharp // Define an authenticated user. private MobileServiceUser user; public async Task<bool> Authenticate() { var success = false; var message = string.Empty; try { // Sign in with Facebook login using a server-managed flow. user = await TodoItemManager.DefaultManager.CurrentClient.LoginAsync(this, MobileServiceAuthenticationProvider.Facebook, "{url_scheme_of_your_app}"); if (user != null) { message = string.Format("you are now signed-in as {0}.", user.UserId); success = true; } } catch (Exception ex) { message = ex.Message; } // Display the success or failure message. AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.SetMessage(message); builder.SetTitle("Sign-in result"); builder.Create().Show(); return success; } public override void OnResume() { base.OnResume(); Xamarin.Essentials.Platform.OnResume(); } ```如果您使用 Facebook 以外的識別提供者,請為 MobileServiceAuthenticationProvider選擇不同的值。
在 元素內新增下列 XML,以更新
<application>檔案:<activity android:name="com.microsoft.windowsazure.mobileservices.authentication.RedirectUrlActivity" android:launchMode="singleTop" android:noHistory="true"> <intent-filter> <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" /> </intent-filter> </activity>將
{url_scheme_of_your_app}取代為您的 URL 架構。在呼叫 之前,將下列程式代碼新增至 MainActivity 類別的
LoadApplication()方法:```csharp // Initialize the authenticator before loading the app. App.Init((IAuthenticate)this); ```此程式代碼可確保驗證器會在應用程式載入之前初始化。
重建應用程式、執行應用程式,然後使用您選擇的驗證提供者登入,並確認您可以以已驗證的使用者身分存取數據。
故障排除
應用程式Java.Lang.NoSuchMethodError: No static method startActivity 當機
在某些情況下,支援套件中的衝突只會在Visual Studio中顯示為警告,但應用程式會在運行時間當機,並出現此例外狀況。 在此情況下,您必須確定項目中參考的所有支援套件都有相同的版本。
Azure Mobile Apps NuGet 套件 具有 Android 平臺 Xamarin.Android.Support.CustomTabs 相依性,因此如果您的專案使用較新的支援套件,您需要直接使用必要的版本安裝此套件,以避免衝突。
將驗證新增至 iOS 應用程式
本節說明如何在 iOS 應用程式項目中實作 IAuthenticate 介面。 如果您不支援 iOS 裝置,請略過本節。
在 Visual Studio 或 Xamarin Studio 中,以滑鼠右鍵點擊 iOS 專案,然後 設定為啟動專案。
按 F5 在除錯程式中啟動項目,然後確認在應用程式啟動時引發狀態代碼為 401(未經授權)的未處理例外狀況。 會產生 401 回應,因為後端的存取僅限於授權的使用者。
在 iOS 項目中開啟AppDelegate.cs,並新增下列
using語句:```csharp using Microsoft.WindowsAzure.MobileServices; using System.Threading.Tasks; ```更新 AppDelegate 類別,以實作 IAuthenticate 介面,如下所示:
```csharp public partial class AppDelegate : global::Xamarin.Forms.Platform.iOS.FormsApplicationDelegate, IAuthenticate ```更新 AppDelegate 類別,新增 MobileServiceUser 字段和 Authenticate 方法,這是 IAuthenticate 介面所需,如下所示:
```csharp // Define an authenticated user. private MobileServiceUser user; public async Task<bool> Authenticate() { var success = false; var message = string.Empty; try { // Sign in with Facebook login using a server-managed flow. if (user == null) { user = await TodoItemManager.DefaultManager.CurrentClient .LoginAsync(UIApplication.SharedApplication.KeyWindow.RootViewController, MobileServiceAuthenticationProvider.Facebook, "{url_scheme_of_your_app}"); if (user != null) { message = string.Format("You are now signed-in as {0}.", user.UserId); success = true; } } } catch (Exception ex) { message = ex.Message; } // Display the success or failure message. UIAlertController avAlert = UIAlertController.Create("Sign-in result", message, UIAlertControllerStyle.Alert); avAlert.AddAction(UIAlertAction.Create("OK", UIAlertActionStyle.Default, null)); UIApplication.SharedApplication.KeyWindow.RootViewController.PresentViewController(avAlert, true, null); return success; } ```如果您使用 Facebook 以外的識別提供者,請為 [MobileServiceAuthenticationProvider] 選擇不同的值。
藉由新增 OpenUrl 方法多載,更新 AppDelegate 類別,如下所示:
```csharp public override bool OpenUrl(UIApplication app, NSUrl url, NSDictionary options) { if (TodoItemManager.DefaultManager.CurrentClient.ResumeWithURL(app, url, options)) return true; return base.OpenUrl(app, url, options); } ```在呼叫 之前,將下列程式碼加入
LoadApplication()方法:```csharp App.Init(this); ```此程式代碼可確保在載入應用程式之前初始化驗證器。
開啟 Info.plist 並新增 URL 類型。 將 識別碼 設為您選擇的名稱、URL 配置 為應用程式的 URL 配置,並將 [角色] 設為 [無]。
重建應用程式、執行應用程式,然後使用您選擇的驗證提供者登入,並確認您可以以已驗證的使用者身分存取數據。
將驗證新增至 Windows 10 (包括 Phone) 應用程式專案
本節說明如何在 Windows 10 應用程式項目中實作 IAuthenticate 介面。 相同的步驟適用於通用 Windows 平臺 (UWP) 專案,但使用 UWP 專案(含已指出的變更)。 如果您不支援 Windows 裝置,請略過本節。
在 Visual Studio 中,以滑鼠右鍵按兩下 UWP 項目,然後 [設定為啟始專案]。
按 F5 在除錯程式中啟動項目,然後確認在應用程式啟動時引發狀態代碼為 401(未經授權)的未處理例外狀況。 401 回應會發生,因為後端的存取僅限於授權的使用者。
開啟 Windows 應用程式項目的MainPage.xaml.cs,並新增下列
using語句:```csharp using Microsoft.WindowsAzure.MobileServices; using System.Threading.Tasks; using Windows.UI.Popups; using <your_Portable_Class_Library_namespace>; ```以可攜式類別庫的命名空間取代
<your_Portable_Class_Library_namespace>。更新 MainPage 類別,以實作 IAuthenticate 介面,如下所示:
public sealed partial class MainPage : IAuthenticate更新 MainPage 類別,新增 MobileServiceUser 欄位和 Authenticate 方法,此為 IAuthenticate 介面的需求,如下所示:
```csharp // Define an authenticated user. private MobileServiceUser user; public async Task<bool> Authenticate() { string message = string.Empty; var success = false; try { // Sign in with Facebook login using a server-managed flow. if (user == null) { user = await TodoItemManager.DefaultManager.CurrentClient .LoginAsync(MobileServiceAuthenticationProvider.Facebook, "{url_scheme_of_your_app}"); if (user != null) { success = true; message = string.Format("You are now signed-in as {0}.", user.UserId); } } } catch (Exception ex) { message = string.Format("Authentication Failed: {0}", ex.Message); } // Display the success or failure message. await new MessageDialog(message, "Sign-in result").ShowAsync(); return success; } ```如果您使用 Facebook 以外的識別提供者,請為 MobileServiceAuthenticationProvider選擇不同的值。
在呼叫 之前,在mainPage
LoadApplication()建構函式中新增下列程式代碼行:```csharp // Initialize the authenticator before loading the app. <your_Portable_Class_Library_namespace>.App.Init(this); ```以可攜式類別庫的命名空間取代
<your_Portable_Class_Library_namespace>。如果您使用 UWP,請將下列 OnActivated 方法覆寫新增至 App 類別:
```csharp protected override void OnActivated(IActivatedEventArgs args) { base.OnActivated(args); if (args.Kind == ActivationKind.Protocol) { ProtocolActivatedEventArgs protocolArgs = args as ProtocolActivatedEventArgs; MobileServiceClientExtensions.ResumeWithURL(TodoItemManager.DefaultManager.CurrentClient,protocolArgs.Uri); } } ```開啟 Package.appxmanifest,並新增 通訊協定 宣告。 將 顯示名稱 設為您選擇的名稱,並將 名稱 設定為應用程式的 URL 配置。
重建應用程式、執行應用程式,然後使用您選擇的驗證提供者登入,並確認您可以以已驗證的使用者身分存取數據。
後續步驟
既然您已完成此基本身份驗證教學課程,請考慮繼續進行下列其中一個教學課程:
-
瞭解如何將推播通知支援新增至您的應用程式,並將行動應用程式後端設定為使用 Azure 通知中樞傳送推播通知。
-
瞭解如何使用行動應用程式後端新增離線支援您的應用程式。 離線同步處理可讓最終使用者與行動應用程式互動 - 檢視、新增或修改資料,即使沒有網路連線也能繼續使用。