How to implement Face ID and Touch ID in a React Native app with Expo?

April 01, 2022 10 min read
implement face id and touch id to react native app with expo

Implementing biometric authentication is no longer a choice; it is a must-have for almost all apps. Devices that run on iOS and Android use the in-built biometrics to ensure proper phone lock systems are in place.

Authentication is now needed to operate your apps. Many banking, messaging, and gaming apps allow you to use the same biometric code (fingerprint, facial recognition) to unlock these apps. It is now essential to understand biometric authentication and how it works. As part of this guide, we will also see how you can implement biometric authentication in your React Native application.

What is Biometric Authentication?

In biometric authentication, the different biological aspects of a human being are used as the password. For example, the retina scan stores and records your unique retina, which is then used to allow you to open the app. similarly, your fingerprints are recorded and used to authenticate you inside the application.

A password can be hacked, which is why most applications now consider recording biometrics that helps them keep the data safe.

The first step to authentication is identification. In the biometric scan, your biometrics are recorded. This is where you offer an identity to the app using your voice, retina, and fingerprints.

Once recorded, this becomes a data set that the app matches every new entrant with to authenticate and allow into the app. The app has learned about you; now, every time someone seeks access to enter, the app will compare the data.

Biometric Authentication: The Process Involved

It is a kind of machine learning example where data sets are compared every single time to ensure that they are a match.

For example, you have submitted your fingerprint on your device to open the banking app. every time you enter the banking app and scan your fingerprint, and it will be matched with the preset data. If there is a match, you will be let into the app.

How Does Biometric Authentication Work?

Let’s look at the logic involved in this process that will help you understand how it works.

In biometric authentication, the device or app allows customers into the app using their touch or face ID. For this purpose, you need to use the LocalAuthentication.authenticateAsync method. When you call for this variable, it will return the value success as true or false. In case true, it means the two sets are a match.

They share a code for when people make multiple attempts, and the screen is locked for a few seconds.

Object {
    "error": "lockout",
    "message": "Too many attempts. Try again later.",
    "success": false,
  },


In this case, the success has turned out to be an error. The user was not aware of the password or forgot it. So, the app/device locked them out for multiple attempts.

In AuthenticateAsync, you can add multiple options using the function LocalAuthenticationOptions. You need to add them as an argument. Here is how the code for the same would appear

LocalAuthenticationOptions = {
    promptMessage?: string; 
    cancelLabel?: string;
    disableDeviceFallback?: boolean;
    fallbackLabel?: string;
  }

Let’s take a look at what each of these options means:

  • PromptMessage: This message is what you see when asked to log in with biometrics. It tells you to scan your retina or fingerprint to access the device/app.
  • CancelLabel: This is another essential function when logging in with biometrics. It makes sure that you can close the biometrics prompt. This is useful if you don’t want to log in using biometrics. In the case of Android devices, you should set the function disableDeviceFallback to true.
  • disableDeviceFallback is the function that allows you to start using the passcode after multiple biometrics trials. It is a much-needed function as there is a good chance the device may not scan your biometrics properly. If you want the customers to use this function to access the passcode, you can keep it false at the default option. In case you want to use biometrics, set it to true.
  • Fallbacklabel: if your disableDeviceFallback is set to false, you will need to set this function. It will help you customize your passcode label.
  • Adding Permissions: You will need to add permissions when creating options for biometric authentication. In Android, these permissions are automatically added to the code. However, in the case of iOs, you will need to add the following code infoPlist.NSFaceIDUsageDescription in the app.json file within the Expo app. you can use a similar code for touch ID to place it in the app.json file. You will then need to place the NSFACEIDUsageDescription within this function so that the app can authenticate the biometric detail.

You are now fully aware of how biometrics works. It is now time to see how to implement biometrics using React Native app and Expo app.

How to Add Biometrics with Expo?

We already know that biometrics tend to compare with pre-set values. So, you will need to make some way to add biometric detail to your application.

Step#1: You will need to install the local authentication file in the expo app. 

// with yarn
yarn add expo-local-authentication

// with npm
npm install expo-local-authentication

You need to run this code to install the local authentication library. Now, you need to install the Npm package for the local authentication. You need to add this code to your TypeScript or JavaScript file
import * as LocalAuthentication from 'expo-local-authentication'

Step#2: Device Compatibility

When you are implementing biometrics, it is a hardware-software combination. You need to check if the hardware supports this authentication method. You will check if the hardware syncs using the hasHardwareAsync method in Expo. 

// wherever the useState is located 
const [isBiometricSupported, setIsBiometricSupported] = React.useState(false);

// Check if hardware supports biometrics
  useEffect(() => {
    (async () => {
      const compatible = await LocalAuthentication.hasHardwareAsync();
      setIsBiometricSupported(compatible);
    })();
  });

// In our JSX we conditionally render a text to see inform users if their device supports
 <Text> {isBiometricSupported ? 'Your device is compatible with Biometrics' 
    : 'Face or Fingerprint scanner is available on this device'}
        </Text>

This async function will return a Boolean value in Promise<Boolean>, which allows you to know if the device supports biometrics.

If there is no support extended for biometrics, you should include alternative login methods such as passcodes in your code.

Step#3: Checking for Records

It is important to note that the system will check with existing biometric records to see if there is a match. You can use the isEnrolledAsync() function to identify this.  

const handleBiometricAuth = async () => {
    const savedBiometrics = await LocalAuthentication.isEnrolledAsync();
      if (!savedBiometrics)
      return Alert.alert(
        'Biometric record not found',
        'Please verify your identity with your password',
        'OK',
        () => fallBackToDefaultAuth()
      );
}

If no biometrics are stored, the app will fall back to the alternative option of using a passcode to enter.

Implementing Biometrics with React Native

For this, you need to use Expo in React Native. You will need to install react-native-uni modules to extract the Expo modules.

You will follow the same method we explained for Expo to install local authentication for your app.

Adding Permissions
We have already discussed this portion when identifying how biometrics work and what are different functions you need to add.
 
// info.plist
<key>NSFaceIDUsageDescription</key>
<string>$(PRODUCT_NAME) Authentication with TouchId or FaceID</string>

With iOS, you will need to add the following code; this is especially true if you are using APIs with access to Face ID.

In case of Android, you need to add these lines:
<uses-permission android:name="android.permission.USE_BIOMETRIC" />
<uses-permission android:name="android.permission.USE_FINGERPRINT" />

We have already discussed this portion when identifying how biometrics work and what are different functions you need to add.

Adding React Native Biometrics

If you want to use a secure way of handling biometrics, you should add react-native-biometrics. It uses both even and result-based methods of authentication.

What does this mean?

  • It doesn’t depend on the Boolean value alone to authenticate
  • It also ensures a cryptographic key is returned to the app, which is sent to the server to authenticate the user to use the application.

If you want to create the authentication flow using this method, start with creating a React Native app.

Initiate this command in the root directory of the app server

Use this command to run the emulator.

You will see a screen that guides you through the process of developing the authentication function. 

You need first to integrate it into your application.
 
yarn add react-native-biometrics
#or
npm install react-native-biometrics


You will need to use the following methods to successfully incorporate authentication to your application.

#1. isSensorAvailable()

the first thing your code should check is whether the device supports biometrics. It will return a Boolean value that will assure of the support.
interface IsSensorAvailableResult {
    available: boolean;
    biometryType?: 'TouchID' | 'FaceID' | 'Biometrics';
    error?: string;
}

Use the following code to check if your Android device extends support for biometrics

import ReactNativeBiometrics from 'react-native-biometrics';

you will have to enter the code that checks for the kind of biometric support available. Does the device support touch and face id both or only one of the two?

You will now have to code if the user has recorded both touch and face ID. You also need to check the IDs.

If you are using iOS, you should use the function ReactNativeBiometrics.TouchID and ReactNativeBiometrics.FaceID. however, in case you are using Android, you should use ReactNativeBiometrics.Biometrics.

Go to settings>security>fingerprint to add a pattern or pin on the emulator. Make sure you log in to the device to add the biometric before testing it out on the device.

You will need to register the fingerprint. For this, you need to use the following code

adb -e emu finger touch <finger_id>
Example: adb -e emu finger touch 5355aw3455

#2. SimplePrompt

This is your prompt essage that appears on the screen along with the biometrics. It also offers a cancel message in case you don’t want to use the biometrics to login. You should also consider adding an error message.

const isBiometricSupport = async () => {
    let {success, error} = await ReactNativeBiometrics.simplePrompt({
      promptMessage: 'Sign in with Touch ID',
      cancelButtonText: 'Close',
    });
    console.log({success, error});
  };

Conclusion

This tutorial was a guide to show you the importance of biometrics, how to implement it in your React Native app, and how this works.

If you don’t have an in-house team that can ably manage the development of the app and integration of biometrics, connect with us. Our team will help you launch the best business solution.

Need a consultation?

Drop us a line! We are here to answer your questions 24/7.

whatsapp icon