Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Adding Biometrics Authentication to Xamarin.iOS and Xamarin.Android

DZone's Guide to

Adding Biometrics Authentication to Xamarin.iOS and Xamarin.Android

Learn how to implement biometric authentication with Touch ID, Face ID, and fingerprint scan for your Azure app with Xamarin.iOS and Xamarin.Android.

· Mobile Zone ·
Free Resource

One of the top Azure App users' requests was to add Touch ID support for additional security. In this post, I will share the details of implementing biometrics authentication for iOS and Android with Xamarin.

There are three aspects of biometric auth:

  1. Enable users to turn biometrics authentication on and off. Users shouldn't be forced to use this additional security feature.
  2. Detecting when the user should be asked for biometric authentication, e.g., when the app is coming from the background and when the app is starting.
  3. Authentication process. Includes detecting hardware capabilities (is Touch or Face ID available?), and local setup (has the user configured local authentication in system settings).

Enabling biometric authentication can usually be controlled in Settings (like in Outlook or OneDrive). We did the same in Azure App:

iOS

Detecting when the user is switching back to our app in iOS is pretty simple. Every time the user switches from the background, the method WillEnterForeground in AppDelegate is being called. We just need to override it with our custom implementation:

public override void WillEnterForeground(UIApplication application)
{
    // biometrics authentication logic here
}

You should also authenticate the user when the app is being launched. In that case, authentication should be performed in your initial view controller.

In iOS, we have two kinds of biometric authentication:

  1. Touch ID
  2. Face ID (available from iPhoneX)

We can also fallback to a passcode if Touch/Face ID is not configured, or the user's device does not support it.

The iOS Local Auth API is pretty straightforward and well documented. I created a simple helper to handle feature detection and authentication:

public static class LocalAuthHelper
{
    private enum LocalAuthType
    {
        None,
        Passcode,
        TouchId,
        FaceId
    }

    public static string GetLocalAuthLabelText()
    {
        var localAuthType = GetLocalAuthType();

        switch (localAuthType)
        {
            case LocalAuthType.Passcode:
                return Strings.RequirePasscode;
            case LocalAuthType.TouchId:
                return Strings.RequireTouchID;
            case LocalAuthType.FaceId:
                return Strings.RequireFaceID;
            default:
                return string.Empty;
        }
    }

    public static string GetLocalAuthIcon()
    {
        var localAuthType = GetLocalAuthType();

        switch (localAuthType)
        {
            case LocalAuthType.Passcode:
                return SvgLibrary.LockIcon;
            case LocalAuthType.TouchId:
                return SvgLibrary.TouchIdIcon;
            case LocalAuthType.FaceId:
                return SvgLibrary.FaceIdIcon;
            default:
                return string.Empty;
        }
    }

    public static string GetLocalAuthUnlockText()
    {
        var localAuthType = GetLocalAuthType();

        switch (localAuthType)
        {
            case LocalAuthType.Passcode:
                return Strings.UnlockWithPasscode;
            case LocalAuthType.TouchId:
                return Strings.UnlockWithTouchID;
            case LocalAuthType.FaceId:
                return Strings.UnlockWithFaceID;
            default:
                return string.Empty;
        }
    }

    public static bool IsLocalAuthAvailable => GetLocalAuthType() != LocalAuthType.None;

    public static void Authenticate(Action onSuccess, Action onFailure)
    {
        var context = new LAContext();
        NSError AuthError;

        if (context.CanEvaluatePolicy(LAPolicy.DeviceOwnerAuthenticationWithBiometrics, out AuthError)
            || context.CanEvaluatePolicy(LAPolicy.DeviceOwnerAuthentication, out AuthError))
        {
            var replyHandler = new LAContextReplyHandler((success, error) =>
            {
                if (success)
                {
                    onSuccess?.Invoke();
                }
                else
                {
                    onFailure?.Invoke();
                }
            });

            context.EvaluatePolicy(LAPolicy.DeviceOwnerAuthentication, Strings.PleaseAuthenticateToProceed, replyHandler);
        }
    }

    private static LocalAuthType GetLocalAuthType()
    {
        var localAuthContext = new LAContext();
        NSError AuthError;

        if (localAuthContext.CanEvaluatePolicy(LAPolicy.DeviceOwnerAuthentication, out AuthError))
        {
            if (localAuthContext.CanEvaluatePolicy(LAPolicy.DeviceOwnerAuthenticationWithBiometrics, out AuthError))
            {
                if (GetOsMajorVersion() >= 11 && localAuthContext.BiometryType == LABiometryType.TypeFaceId)
                {
                    return LocalAuthType.FaceId;
                }

                return LocalAuthType.TouchId;
            }

            return LocalAuthType.Passcode;
        }

        return LocalAuthType.None;
    }

    private static int GetOsMajorVersion()
    {
        return int.Parse(UIDevice.CurrentDevice.SystemVersion.Split('.')[0]);
    }
}

There are helper methods determining the proper label ( GetLocalAuthLabelText), icon ( GetLocalAuthIcon) and authentication text ( GetLocalAuthUnlockText) depending on the available authentication type. There is also a one-liner IsLocalAuthAvailable checking if Local Authentication (Face/Touch ID or passcode) is available, and Authenticate method that performs authentication, which takes success and failure callbacks as parameters. It can be used in the WillEnterForeground method as follows:

public override void WillEnterForeground(UIApplication application)
{
    if (!AppSettings.IsLocalAuthEnabled)
    {
        return;
    }

    LocalAuthHelper.Authenticate(null, // do not do anything on success
    () =>
    {
        // show View Controller that requires authentication
        InvokeOnMainThread(() =>
        {
            var localAuthViewController = new LocalAuthViewController();
            Window.RootViewController.ShowViewController(localAuthViewController, null);
        });
    });
}

We do not have to do anything on success. The popup shown by iOS will disappear and the user will be able to use the app. On failed authentication, though, we should display some kind of shield (e.g. ViewController) that prevents the user from using the app until authorization succeeds. This is how it looks in Azure App:

Android

Detecting when the app is coming from the background in Android is tricky. There is no single method that is invoked only when the app is coming back from the background. The OnResume method is being called when the app is coming back from the background, but it's also called when you switch from one activity to another. The solution for that is to keep a timestamp with the last successful authentication and update it to DateTime.Now every time the activity is calling OnPause. This happens when the app is going to the background, but also when the app is changing between activities. Thus, we cannot simply set the flag Background=true when OnPause is called. However, when the difference between the subsequent OnPause and OnResume is larger than some period of time (e.g. more than a few seconds), we can assume that the app went to the background. The code below should be implemented in some BaseActivity class that all activities inherit from:

public class BaseActivity
{
  public const int FingerprintAuthTimeoutSeconds = 5;
  public static DateTime LastSuccessfulFingerprintAuth = DateTime.MinValue;

  protected override void OnResume()
  {
    base.OnResume();

    if (IsFingerprintAvailable() && LastSuccessfulFingerprintAuth > DateTime.Now.AddSeconds(-FingerprintAuthTimeoutSeconds))
    {
      StartActivity(typeof(FingerprintAuthActivity));
    }
  }

  protected override void OnPause()
  {
    base.OnPause();

    if (IsFingerprintAvailable())
    {
      LastSuccessfulFingerprintAuth = DateTime.Now;
    }
  }
}

The basics of Fingerprint authentication are very well described in the Xamarin docs.

An even better reference is the sample app FingerprintGuide from Xamarin.

The main disadvantage of adding fingerprint authentication in Android (over Face/Touch ID in iOS) is the requirement to build your own UI and logic for the authentication popup. This includes adding an icon and handling all authentication results. iOS handles incorrect scans and displays the popup again with a passcode fallback after too many unsuccessful tries. In Android, you have to implement this entire logic by yourself.

Summary

Adding biometrics authentication is useful for apps that hold sensitive data, like banking apps, file managers (Dropbox, OneDrive), or an app that has access to your Azure Resources.

Implementing local authentication in iOS is pretty straightforward, and iOS APIs provide the authentication UI for free. In Android, however, the APIs only work with the backend, and the UI has to be implemented by you.

Local authentication should be always optional. Some users may not need nor want it. Thus, it should be configurable in the app settings.

Try out biometric auth in Azure App!

Topics:
xamarin ,mobile ,mobile app development ,authentication ,biometric authentication ,azure ,ios ,android ,tutorial ,mobile security

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}