Using biometric identification in Xamarin Forms

xamarin fingerprint biometrics

In this new post, I’m going to explain how using biometric identification in Xamarin Forms. It’s very likely that some of the applications that you have installed on your device uses fingerprints to simplify authentication before executing certain important or sensitive actions. We usually see this type of features in banking applications where you decide whether to access with your credentials or your fingerprint! And honestly I love using my fingerprint because it saves me a lot of time! ?

And it’s very easy to implement in Xamarin Forms! In this article we will be learning how to do it! If you need the source code of this post, as usual, you can find it on GitHub.

First of all, you have to take in consideration before implementing fingerprint in your project that:

  • Not all devices have fingerprint recognition, therefore not 100% of your users will take advantage of this feature, for this reason it is extremely important to implement fingerprint identification as an additional option that is NOT unique.
  • You can’t store the fingerprint received.

Add Plugin.FingerPrint

So, right-click on the solution and open the Manage Packages for Solution. Now, search for Plugin.Fingerprint (here the NuGet package) and add it to all the projects.

Add a Nuget package

Configure project for iOS

First, we have to configure the Info.plist to allow the app using the biometrics. For that, right-click on the file and select View Code.

View code for Info.plist - Using biometric identification in Xamarin Forms
View code for Info.plist

So, you can see the XML of the file. You can immediately identified the <dict> tag. Before closing this tag, add the following lines:

<key>NSFaceIDUsageDescription</key>
<string>It’s required for login authentication.</string>

In the description in <string> tag add the purpose of using your Face ID in your App. For example: It’s required for login authentication. 

So, it’s important to add this description if not your App will crash when you start a Face ID authentication on iOS 11.3+.

Configure project for Android

Open you AndroidManifest.xml and check the UseFingerPrint permission. You can use Visual Studio for that. Right-click on the Android project and then click on Properties.

Properties for the Android project - Using biometric identification in Xamarin Forms
Properties for the Android project

Then, click on Android Manifest tab and in the section Required permissions check the properties USE_FINGERPRINT.

Use Fingerprint in the Android project
Use Fingerprint in the Android project

Then, open your MainActivity.cs and after Xamarin.Forms initialization add the following code:

CrossFingerprint.SetCurrentActivityResolver(() => this);

Remember to add the using for the package.

Add code to the project

First, add a new page called SecretPage and this is the content (pretty simple).

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="https://xamarin.com/schemas/2014/forms"
             xmlns:x="https://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="XamBiometric.SecretPage">
    <ContentPage.Content>
        <StackLayout>
            <Label Text="This is a secret page"
                VerticalOptions="CenterAndExpand" 
                HorizontalOptions="CenterAndExpand" />
        </StackLayout>
    </ContentPage.Content>
</ContentPage>

Change the UI for MainPage.xaml

Then, I want to create a simple form where I want to display:

  • a label to display the type of authentication, for example Fingerprint, that comes from the Fingerprint component
  • 3 switches for
    • allow the user to cancel the biometric request automatically after 10 seconds
    • allow alternative authentication method such as password and PIN
    • Require confirmation
  • a button for the authentication
  • a button for localized authentication

Here the code with a bit of style

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="https://xamarin.com/schemas/2014/forms"
             xmlns:x="https://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="XamBiometric.MainPage">

	<StackLayout>
		<Frame BackgroundColor="#2196F3" Padding="24" CornerRadius="0">
			<Label Text="Biometric Demo" HorizontalTextAlignment="Center" TextColor="White" FontSize="36"/>
		</Frame>
		<Label x:Name="lblAuthenticationType" Padding="30,10,30,10"></Label>
		<StackLayout Orientation="Horizontal" Padding="30,10,30,10">
			<StackLayout.IsVisible>
				<OnPlatform x:TypeArguments="x:Boolean">
					<On Platform="Android">True</On>
					<On Platform="iOS">True</On>
				</OnPlatform>
			</StackLayout.IsVisible>
			<Switch x:Name="swAutoCancel"></Switch>
			<Label Text="Cancel after 10sec"></Label>
		</StackLayout>
		<StackLayout Orientation="Horizontal" Padding="30,10,30,10">
			<StackLayout.IsVisible>
				<OnPlatform x:TypeArguments="x:Boolean">
					<On Platform="Android">True</On>
					<On Platform="iOS">True</On>
				</OnPlatform>
			</StackLayout.IsVisible>
			<Switch x:Name="swAllowAlternative"></Switch>
			<Label Text="Allow alternative authentication method (Password / PIN)"></Label>
		</StackLayout>
		<StackLayout Orientation="Horizontal" Padding="30,10,30,10">
			<StackLayout.IsVisible>
				<OnPlatform x:TypeArguments="x:Boolean">
					<On Platform="Android">True</On>
					<On Platform="iOS">False</On>
				</OnPlatform>
			</StackLayout.IsVisible>
			<Switch x:Name="swConfirmationRequired" IsToggled="True"></Switch>
			<Label Text="Require Confirmation"></Label>
		</StackLayout>
		<Button Text="Authenticate" Clicked="OnAuthenticate" Padding="30,10,30,10"></Button>
		<Button Text="Authenticate localized" Clicked="OnAuthenticateLocalized" Padding="30,10,30,10"></Button>
		<Label x:Name="lblStatus" Padding="30,10,30,10"></Label>
	</StackLayout>
</ContentPage>

Change MainPage.xaml.cs

Now, the focus is on MainPage.xaml.cs. At the top of the code, add the following code

private CancellationTokenSource _cancel;
private bool _initialized;

and remember to add the using

using Plugin.Fingerprint.Abstractions;
using System.Threading;

So, when the page is appearing, we want to initialize the CrossFingerprint. For that, add the following code

protected override async void OnAppearing()
{
    base.OnAppearing();

    if (!_initialized)
    {
        _initialized = true;
        lblAuthenticationType.Text = "Auth Type: " + await Plugin.Fingerprint.CrossFingerprint.Current.GetAuthenticationTypeAsync();
    }
}

private async void OnAuthenticate(object sender, EventArgs e)
{
    await AuthenticateAsync("Prove you have fingers!");
}

private async void OnAuthenticateLocalized(object sender, EventArgs e)
{
    await AuthenticateAsync("Beweise, dass du Finger hast!", "Abbrechen", "Anders!", "Viel zu schnell!");
}

Now, I’m going to add the authentication part

private async Task AuthenticateAsync(string reason, string cancel = null, 
                                     string fallback = null, string tooFast = null)
{
    _cancel = swAutoCancel.IsToggled ? 
              new CancellationTokenSource(TimeSpan.FromSeconds(10)) : 
              new CancellationTokenSource();
    lblStatus.Text = "";

    var dialogConfig = new AuthenticationRequestConfiguration("XamBiometric", reason)
    { 
        // all optional
        CancelTitle = cancel,
        FallbackTitle = fallback,
        AllowAlternativeAuthentication = swAllowAlternative.IsToggled,
        ConfirmationRequired = swConfirmationRequired.IsToggled
    };

    // optional
    dialogConfig.HelpTexts.MovedTooFast = tooFast;

    var result = await Plugin.Fingerprint.CrossFingerprint.Current.AuthenticateAsync(
                         dialogConfig, _cancel.Token);

    SetResult(result);
}

private void SetResult(FingerprintAuthenticationResult result)
{
    if (result.Authenticated)
    {
        var navPage = new NavigationPage(new SecretPage());
        Application.Current.MainPage = navPage;
    }
    else
    {
        lblStatus.Text = $"{result.Status}: {result.ErrorMessage}";
    }
}

What if you don’t have a physical device?

So, you can test it in your emulator! Let’s learn how to do it!

  • on iPhone: With the simulator open , go to device ➡ Features ➡ Face ID ➡ Enrolled.
  • on Android: Locate you emulator ➡ Settings (…) ➡ Fingerprint ➡ Click on “Touch the sensor” button (not from the simulator in Visual Studio for Windows)

iOS result

Now, it you want to try this project in a simulator from your Windows machine, you can’t try the fingerprint or FaceID simple because in the simulator there is not option for that.

What we have to do is to run the app in your iMac. So, after the app starts in the simulator, you have the first page of the application like in the following picture.

iOS XamBiometric home page - OS result - Using biometric identification in Xamarin Forms
iOS XamBiometric home page

Now, to enable the simulator to emulate the fingerprint or FaceID, you have to enrol it. So, in the Simulator menu, click on Features, then Face ID and then Enrolled.

So, you can click the Authenticate button and immediately there is prompt to allow or now the use of Face ID.

iOS XamBiometric: prompt to allow to use Face ID
iOS XamBiometric: prompt to allow to use Face ID

Press OK. Now, iOS is waiting for the confirmation with Face ID. For that, in the menu Features, under Face ID, select Matching face if you want to try to happy path or Non-matching face to test the other path.

Face ID is waiting for facing recognition
Face ID is waiting for facing recognition

Android result

So, this is the first page of the app that runs in a simulator. It is pretty cute!

Android fingerprint in action

Because I can’t take a screenshot when there is a authentication request, I took a picture of the app in my real device. How you can see, there is a popup with the name of the app, a description and then the invite to touch the fingerprint sensor.

The result on a real device
The result on a real device

Universal Windows Platform (UWP) result

Now, the code is working also for Universal Windows Platform (UWP). If you run the app in your Windows machine, and click on the Authenticate button, Windows opens the Windows Security for Windows Hello, checks my identity and then I can press OK to continue.

Biometrics with UWP
Biometrics with UWP

Conclusion

So, in this post we learn how using biometric identification in Xamarin Forms with Plugin.Fingerprint. I hope you enjoy it! As usual, I have published the full source code of this post on GitHub. If you have any issues, please open a new thread in the Forum.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.