Add authentication to your Xamarin.Forms app

In this tutorial, add Microsoft authentication to your app using Azure Active Directory. Before completing this tutorial, ensure you have created the project and enabled offline sync.

Configure your backend for authentication

To configure your backend for authentication, you must:

  • Create an app registration.
  • Configure Azure App Service Authentication and Authorization.
  • Add your app to the Allowed External Redirect URLs.

During this tutorial, we'll configure your app to use Microsoft authentication. An Azure Active Directory tenant has been configured automatically in your Azure subscription. You can use Azure Active Directory to configure Microsoft authentication.

You will need the URL of the Azure Mobile Apps service. The backend URL was provided when you created your project.

Create an app registration

  1. Sign in to the Azure portal.
  2. Select Azure Active Directory > App registrations > New registration.
  3. In the Register an application page, enter zumoquickstart in the Name field.
  4. Under Supported account types, select Accounts in any organizational directory (Any Azure AD directory - multitenant) and personal Microsoft accounts (e.g. Skype, Xbox).
  5. In Redirect URI, select Web and type <backend-url>/.auth/login/aad/callback. For example, if your backend URL is https://zumo-abcd1234.azurewebsites.net, you would enter https://zumo-abcd1234.azurewebsites.net/.auth/login/aad/callback.
  6. Press the Register button at the bottom of the form.
  7. Copy the Application (client) ID.
  8. From the left pane, select Certificates & secrets > New client secret.
  9. Enter a suitable description, select a validity duration, then select Add.
  10. Copy the secret on the Certificates & secrets page. The value won't be displayed again.
  11. Select Authentication.
  12. Under Implicit grant and hybrid flows, enable ID tokens.
  13. Press Save at the top of the page.

Important

The client secret value (password) is an important security credential. Don't share the password with anyone or distribute it within a client application.

Configure Azure App Service Authentication and Authorization

  1. In the Azure portal, select All Resources, then your App Service.
  2. Select Settings > Authentication.
  3. Press Add identity provider.
  4. Select Microsoft as the identity provider. This will provide a form to fill in.
  5. For App registration type, select Provide the details of an existing app registration.
  6. Paste the values you copied earlier into the Application (client) ID and Client secret boxes.
  7. For Issuer URL, enter https://login.microsoftonline.com/9188040d-6c67-4c5b-b112-36a304b66dad/v2.0. This URL is the "magic tenant url" for Microsoft logins.
  8. For Restrict access, select Require authentication.
  9. For Unauthenticated request, select HTTP 401 Unauthorized.
  10. Press Add.
  11. Once the authentication screen returns, press Edit next to Authentication settings.
  12. In the Allowed external redirect URLs box, enter zumoquickstart://easyauth.callback.
  13. Press Save.

Step 10 requires that all users are authenticated before accessing your backend. You can provide fine-grained controls by adding code to your backend. For more information, see the Server SDK How-to for Node.js or ASP.NET Framework.

DID YOU KNOW? You can also allow users with organizational accounts in Azure Active Directory, Facebook, Google, Twitter, or any OpenID Connect compatible provider. Follow the instructions in the Azure App Service documentation.

Test that authentication is being requested

  • Open your project in Android Studio.
  • From the Run menu, press Run app.
  • Verify that an unhandled exception with a status code of 401 (Unauthorized) is raised after the app starts.

Add authentication to the app

Authentication is handled differently on each platform. First, add a required method to the Utils\IAppContext.cs interface:

using Microsoft.WindowsAzure.MobileServices;
using System.Threading.Tasks;

namespace ZumoQuickstart
{
    public interface IAppContext
    {
        // Place any methods required on the main entry-point here.
        Task<bool> AuthenticateAsync(MobileServiceClient client);
    }
}

Open the TodoService.cs class. Edit the InitializeAsync() method to request authentication:

    // Get a reference to the table.
    mTable = mClient.GetSyncTable<TodoItem>();

    // Add the following line:
    await mContext.AuthenticateAsync(mClient).ConfigureAwait(false);

    isInitialized = true;

Add authentication to the Android app

Open the MainActivity.cs class in the ZumoQuickStart.Android project. Add the following method to the class:

public async Task<bool> AuthenticateAsync(MobileServiceClient client)
{
    try
    {
        var user = await client.LoginAsync(this, "aad", "zumoquickstart").ConfigureAwait(false);
        return user != null;
    }
    catch (Exception error)
    {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.SetMessage(error.Message);
        builder.SetTitle("Sign in result");
        builder.Create().Show();
        return false;
    }
}

Edit the Properties\AndroidManifest.xml to register the authentication response handler:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" android:versionCode="1" android:versionName="1.0" package="com.companyname.zumoquickstart">
    <uses-sdk android:minSdkVersion="21" android:targetSdkVersion="28" />
    <application android:label="ZumoQuickstart.Android" android:theme="@style/MainTheme">
      <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="zumoquickstart" android:host="easyauth.callback" />
        </intent-filter>
      </activity>      
    </application>
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
</manifest>

You can now run the Android app in the emulator. It will prompt you for a Microsoft credential before showing you the list of items.

Add authentication to the iOS app

Open the AppDelegate.cs class in the ZumoQuickstart.iOS project. Add the following code to the end of the class:

    public override bool OpenUrl(UIApplication app, NSUrl url, NSDictionary options)
        => Xamarin.Essentials.Platform.OpenUrl(app, url, options);

    public Task<bool> AuthenticateAsync(MobileServiceClient client)
    {
        var tcs = new TaskCompletionSource<bool>();
        var view = UIApplication.SharedApplication.KeyWindow.RootViewController;

        Device.BeginInvokeOnMainThread(async () =>
        {
            try
            {
                var user = await client.LoginAsync(view, "aad", "zumoquickstart");
                tcs.TrySetResult(user != null);
            }
            catch (Exception error)
            {
                var alert = UIAlertController.Create("Sign-in result", error.Message, UIAlertControllerStyle.Alert);
                alert.AddAction(UIAlertAction.Create("OK", UIAlertActionStyle.Default, null));
                view.PresentViewController(alert, true, null);
                tcs.TrySetResult(false);
            }
        });

        return tcs.Task;
    }

Right-click on the Info.plist file, then select Open with.... Select the XML (Text) Editor. Add the following to the file right before the final </dict> line.

    <key>CFBundleURLTypes</key>
    <array>
      <dict>
        <key>CFBundleURLName</key>
        <string>URL Type 1</string>
        <key>CFBundleURLSchemes</key>
        <array>
          <string>zumoquickstart</string>
        </array>
        <key>CFBundleTypeRole</key>
        <string>None</string>
      </dict>
    </array>

After the user completes the sign-in, the user will be redirected back to the application. You can now build and run the application. The user is prompted to sign-in before the list of items is displayed.

Add authentication to the UWP app

Open the App.xaml.cs file within the ZumoQuickstart.UWP project. Add the following code to the end of the class:

    public static MobileServiceClient CurrentClient { get; set; } = null;

    protected override void OnActivated(IActivatedEventArgs args)
    {
        base.OnActivated(args);
        if (args.Kind == ActivationKind.Protocol)
        {
            MobileServiceClientExtensions.ResumeWithURL(CurrentClient, (args as ProtocolActivatedEventArgs).Uri);
        }
    }

This calls the response handler within Azure Mobile Apps when the response from the authentication service is received.

Open the MainPage.xaml.cs file and add the following code to the end of the class:

    public Task<bool> AuthenticateAsync(MobileServiceClient client)
    {
        var tcs = new TaskCompletionSource<bool>();
        Device.BeginInvokeOnMainThread(async () =>
        {
            try
            {
                var user = await client.LoginAsync("aad", "zumoquickstart");
                tcs.TrySetResult(user != null);
            }
            catch (Exception error)
            {
                var dialog = new MessageDialog(error.Message, "Sign-in error");
                await dialog.ShowAsync();
                tcs.TrySetResult(false);
            }
        });

        return tcs.Task;
    }

Finally, register the "zumoquickstart" protocol:

  • Open the Package.appxmanifest file.
  • Select the Declarations tab.
  • Under Available Declarations, select Protocol and then press Add.
  • Fill in the form as follows:
    • Display name: Authentication Response
    • Name: zumoquickstart
    • ExecutableOrStartPageIsRequired: checked All other fields can be left blank.

You can now build and run the application. When it runs, the sign-in process will be triggered prior to the list of items being displayed.

Test the app

From the Run menu, press Run app to start the app. You'll be prompted for a Microsoft account. When you're signed in, the app should run as before without errors.

Deleting the resources

Now you've completed the quickstart tutorial, you can delete the resources with az group delete -n zumo-quickstart. You can also delete the global app registration used for authentication through the portal.

Next steps

Take a look at the HOW TO sections:

You can also do a Quick Start for another platform using the same backend server:

Learn more about developing cross-platform apps with Xamarin.Forms and Azure Mobile Apps with a free book.