Add authentication to your Xamarin.iOS app

In this tutorial, you add Microsoft authentication to the quickstart project on Xamarin.iOS 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.
  • Press F5 to run the app.
  • Verify that an unhandled exception with a status code of 401 (Unauthorized) is raised after the app starts.

Add authentication to the app

Open the TodoService.cs class. Add the AuthenticateAsync() method to the class:

private Task<bool> AuthenticateAsync()
{
  var tcs = new TaskCompletionSource<bool>();
  Xamarin.Essentials.MainThread.BeginInvokeOnMainThread(async () =>
  {
    var rootController = UIApplication.SharedApplication.KeyWindow.RootViewController;
    try
    {
      var user = await mClient.LoginAsync(rootController, "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));
      rootController.PresentViewController(alert, true, null);
      tcs.TrySetResult(false);
    }
  });

  return tcs.Task;
}

Use Alt+Enter to add the required package (UIKit). Edit the InitializeAsync() method to request authentication:

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

    await AuthenticateAsync();

    isInitialized = true;

Open the SceneDelegate.cs class. Add the following code to the end of the class:

[Export("scene:openURLContexts:")]
public void OpenUrlContexts(UIScene scene, NSSet<UIOpenUrlContext> urlContexts)
{
  var context = urlContexts.AnyObject;
  if (context == null) return;
  var url = context.Url;
  var options = context.Options == null ? null : new UIApplicationOpenUrlOptions
  {
    Annotation = context.Options.Annotation,
    OpenInPlace = context.Options.OpenInPlace,
    SourceApplication = context.Options.SourceApplication
  };
  Xamarin.Essentials.Platform.OpenUrl(UIApplication.SharedApplication, url, options.Dictionary);
}

The OpenUrlContexts method handles the callback from the web authenticator on iOS 13 and later. For other iOS versions, follow the instructions in the Xamarin.Essentials documentation.

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>

iOS uses this information to redirect the user back to the app once they have signed in. You can now build and run the application. The sign-in process will be triggered immediately.

Test the app

Press F5 to run the app. When you're successfully 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: