Add authentication to your Xamarin.Android app

In this tutorial, add Microsoft authentication to your app using Azure Active Directory. Before completing this tutorial, ensure you've 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 Visual 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.

The app attempts to access the service as an anonymous user. The TodoItem table now requires authentication, so the server responds with a 401 Unauthorized HTTP status code.

Add authentication to the app

Update the TodoService.cs class so that the app asks for sign-in when initializing the service. Add a constructor:

    private Android.Content.Context mContext;

    public TodoService(Android.Content.Context context)
    {
        mContext = context;
    }

Then, edit the InitializeAsync() method to add the sign-in call:

    private async Task InitializeAsync()
    {
        using (await initializationLock.LockAsync())
        {
            if (!isInitialized)
            {
                // Create the client.
                mClient = new MobileServiceClient(Constants.BackendUrl, new LoggingHandler());

                // Define the offline store.
                mStore = new MobileServiceSQLiteStore("todoitems.db");
                mStore.DefineTable<TodoItem>();
                await mClient.SyncContext.InitializeAsync(mStore).ConfigureAwait(false);

                // Authenticate the user
                await mClient.LoginAsync(mContext, "aad", "zumoquickstart");

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

Edit the MainActivity.cs file to pass the context into the service within the OnCreate() method:

    // Azure Mobile Apps
    CurrentPlatform.Init();
    todoService = new TodoService(this);

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.

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: