Skip to content

Biometric Authentication (Fingerprint-Face ID) in React Native with expo

In today’s digital world, security is paramount. Users demand secure and convenient ways to access their sensitive information. Biometric authentication, such as fingerprint recognition and Face ID, has revolutionized user authentication on mobile devices. In this article, we’ll explore how to implement biometric authentication like fingerprint in Android and Face ID for iOS apps using React Native and Expo.

Table of Contents

  1. Introduction to Biometric Authentication
  2. Setting Up the Project
  3. Implementing Biometric Authentication for Android and Face ID for IOS
  4. Conclusion

Introduction to Biometric Authentication Fingerprint | Face ID

Biometric authentication involves using unique biological characteristics, such as fingerprints or facial features, to verify a user’s identity. It offers a more secure and user-friendly alternative to traditional methods like PINs and passwords. Android devices commonly use fingerprint authentication, while iOS devices leverage Face ID for facial recognition. So, in this article we talk about how to implement both.

Final Demonstration of code on android for fingerprint:

This code also works on ios for Face ID as currently I do not have ios emulator so I cannot demonstrate you.

Setting Up Your Development Environment

  1. Install Node.js: If you haven’t already, download and install Node.js.
  2. Install Expo CLI: Open a command prompt and run the following command to install the Expo CLI:
npm install -g expo-cli

Create a New Expo Project: Create a new Expo project by running:

expo init BiometricApp

Navigate to Project Directory: Move to your project directory:

cd BiometricApp

Install Dependencies: Install the necessary dependencies:

npm install expo-local-authentication

Implementing Biometric Authentication for Android and Face ID for IOS

Create a new component (e.g., BiometricScreen.js) and use the following code as an example:

import React from 'react';
import { View, Text, TouchableOpacity } from 'react-native';
import * as LocalAuthentication from 'expo-local-authentication';

export default function BiometricScreen() {
  const authenticateWithBiometric = async () => {
    try {
      const isBiometricAvailable = await LocalAuthentication.hasHardwareAsync();
      
      if (isBiometricAvailable) {
        const supportedTypes = await LocalAuthentication.supportedAuthenticationTypesAsync();
        
        if (supportedTypes.includes(LocalAuthentication.AuthenticationType.FINGERPRINT)) {
          // Fingerprint authentication for Android
          const result = await LocalAuthentication.authenticateAsync({
            promptMessage: 'Authenticate to access your account.',
          });

          if (result.success) {
            alert('Authentication Successful');
          } else {
            alert('Authentication Failed');
          }
        } else if (supportedTypes.includes(LocalAuthentication.AuthenticationType.FACIAL_RECOGNITION)) {
          // Face ID authentication for iOS
          const result = await LocalAuthentication.authenticateAsync({
            promptMessage: 'Authenticate to access your account.',
            disableDeviceFallback: true, // Prevents fallback to PIN/passcode
          });

          if (result.success) {
            alert('Authentication Successful');
          } else {
            alert('Authentication Failed');
          }
        } else {
          alert('Biometric authentication is not available on this device.');
        }
      } else {
        alert('Biometric hardware is not available on this device.');
      }
    } catch (error) {
      console.error('Biometric authentication error:', error);
    }
  };

  return (
    <View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
      <Text style={{ marginBottom: 20 }}>
        Biometric Authentication Example
      </Text>
      <TouchableOpacity
        onPress={authenticateWithBiometric}
        style={{
          backgroundColor: 'blue',
          padding: 10,
          borderRadius: 5,
        }}
      >
        <Text style={{ color: 'white' }}>Authenticate with Biometric</Text>
      </TouchableOpacity>
    </View>
  );
}

Understanding the Code:

This code handles both fingerprint authentication on Android and Face ID authentication on iOS using Expo’s unified expo-local-authentication package. It checks for hardware availability, supported authentication types, and provides a consistent user experience across devices.

1. Imports and Setup

In order to implement biometric authentication in a React Native app, we start by importing the necessary components and the expo-local-authentication package. This package provides access to biometric authentication methods across different platforms, making it a key tool for integrating this feature seamlessly.

2. Function authenticateWithBiometric

The core of our biometric authentication process lies within the authenticateWithBiometric function. This function is enclosed within a try-catch block to ensure that any potential errors during the authentication process are gracefully handled.

3. Check Biometric Hardware Availability

Before diving into the authentication process, we use the LocalAuthentication.hasHardwareAsync() function. This function helps us determine whether the device has the necessary biometric hardware, such as a fingerprint sensor or Face ID recognition.

4. Handling Available Biometric Types

If the device does have biometric hardware available, we move on to the next step: determining the supported biometric authentication types. This is achieved using LocalAuthentication.supportedAuthenticationTypesAsync(). The function returns an array of supported authentication types, which may include options like fingerprint or facial recognition.

5. Fingerprint Authentication for Android

For devices that support fingerprint authentication (indicated by LocalAuthentication.AuthenticationType.FINGERPRINT), we utilize the LocalAuthentication.authenticateAsync() method. This initiates the fingerprint authentication process and presents a prompt message to the user. The result is awaited, and based on whether the authentication is successful, an alert is displayed indicating either success or failure.

6. Face ID Authentication for iOS

For devices with facial recognition capabilities (identified by LocalAuthentication.AuthenticationType.FACIAL_RECOGNITION), we employ the same LocalAuthentication.authenticateAsync() method. However, in this case, we set disableDeviceFallback to true to prevent the authentication process from falling back to PIN/passcode. Similar to fingerprint authentication, the result of the authentication attempt triggers an alert that indicates success or failure.

7. Handling Unsupported Biometric Types

In the event that neither fingerprint nor facial recognition is supported on the device, our code alerts the user that biometric authentication is not available.

8. Handling No Biometric Hardware

If the device lacks biometric hardware altogether, the user is informed through an alert that their device does not possess the necessary components for biometric authentication.

9. Return UI Component

Finally, the UI component is returned, showcasing a straightforward button that triggers the authenticateWithBiometric function upon being pressed. This button serves as the user interface for initiating the biometric authentication process.

Please note that this guide provides a comprehensive overview of the steps and logic involved in implementing biometric authentication in a React Native app using the expo-local-authentication library. By following these steps and understanding the underlying code structure, you’ll be well-equipped to integrate this advanced security feature into your own app with confidence.

Conclusion

Congratulations! You’ve successfully implemented biometric authentication in your React Native app using Expo’s expo-local-authentication package. Now your users can securely access their accounts with the convenience of biometric verification on both Android and iOS devices.

Remember to consider device-specific behavior and limitations when implementing biometric authentication. Always test your app on various devices to ensure a consistent and reliable user experience.

Leave a Reply

Your email address will not be published. Required fields are marked *