DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Because the DevOps movement has redefined engineering responsibilities, SREs now have to become stewards of observability strategy.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Related

  • Unlocking Seamless Experiences: Embracing Passwordless Login for Effortless Customer Registration and Authentication
  • Configuring SSO Using WSO2 Identity Server
  • Turn Your App into a Handy Health Assistant
  • How To Integrate Third-Party Login Systems in Your Web App Using OAuth 2.0

Trending

  • Designing Fault-Tolerant Messaging Workflows Using State Machine Architecture
  • Agentic AI Systems: Smarter Automation With LangChain and LangGraph
  • Exploring Intercooler.js: Simplify AJAX With HTML Attributes
  • Building a Real-Time Change Data Capture Pipeline With Debezium, Kafka, and PostgreSQL

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.

By 
Jacob Jedryszek user avatar
Jacob Jedryszek
·
Jan. 31, 18 · Tutorial
Likes (5)
Comment
Save
Tweet
Share
26.2K Views

Join the DZone community and get the full member experience.

Join For Free

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!

authentication app

Published at DZone with permission of Jacob Jedryszek, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Unlocking Seamless Experiences: Embracing Passwordless Login for Effortless Customer Registration and Authentication
  • Configuring SSO Using WSO2 Identity Server
  • Turn Your App into a Handy Health Assistant
  • How To Integrate Third-Party Login Systems in Your Web App Using OAuth 2.0

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!