How To Implement Face Id And Touch Id In React Native And Expo

October 04, 2021 Publish By : EXPERT APP DEVS 7 min read Viewed By : 903
face id and touch id in react native and expo

Introduction -

In this article, we are going to learn about the most complicated react-native topic, which is biometric registration and there are lots of biometric options but here we discuss only face id and touch id registration. 

face id and touch id in react native and expo framework

Biometric Introduction -

Biometric authentication is a part of multifactor authentication, which is derived from the user’s device by biological traits, such as voice recognition, facial characteristics, and fingerprints, to protect personal information and sensitive data.

All kinds of mobile apps are using local biometric authentication.  Biometric authentication is performed entirely within the user’s device and that is the best part of biometric, so there is no risk of leaking data to a third-party API.

So let’s start the tutorial integration.

Biometric authentication implementation in an Expo app - 

Follow all the steps carefully for integration authentication in your expo app.

Step 1 - 

First, we need to do the installation, run the following command to install the expo-local-authentication library.

// with npm

npm install expo-local-authentication

Step 2 - 

Now we need to import the expo-local-authentication
Library where we want to integrate it.

import * as LocalAuthentication from 'expo-local-authentication'

Step 3 - 

Now we need to check the device hardware compatibility if the device has biometric functionality or not.
 
We’ll use the hasHardwareAsync method which is provided by the Expo to check the compatibility.

// 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' 

    : 'biomatric scanner is available on this device'}

        </Text>

Step 4 - 

Now we need to check the biometric records which are saved on the user's device.
For this we use the isEnrolledAsync method. This method returns a promise isEnrolledAsync(): Promise<boolean>.

Below is a code of - 

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()

      );

}

Step 5 - 

In this step, we see how biometrics works.
To authenticate users via fingerprint scan or Face ID/Touch ID, we are going to use the LocalAuthentication.authenticateAsync. This method returns a promise of success, which can be true or false.

payload returned when success is false.

Object {

    "error": "lockout",

    "message": "Too many attempts. Try again later.",

    "success": false,

  },

Here are some important props - 

  • LocalAuthenticationOptions

LocalAuthenticationOptions = {

    promptMessage?: string; 

    cancelLabel?: string;

    disableDeviceFallback?: boolean;

    fallbackLabel?: string;
 }

  • promptMessage - message for showing TouchID or FaceID prompt.
  • cancelLabel - It allows the user to change the label of the cancel text.

Biometric authentication implementation in a React Native CLI app -

Here we are going to implement the face id and touch id in react native apps by using CLI.
By using react-native-unimodules this 3 - party library will implement the biometric functionality, you can implement it in react native app same as expo do.

And there is another way too, we discuss one more library.

Step 1 - 

First, we need to install the third-party library which is react-native-touch-id.

npm i --save react-native-touch-id

Step 2 - 

After installing a third-party library successfully, now we need to import it where we want to implement this functionality.

import TouchID from 'react-native-touch-id'

Step 3 - 

Now you need to link the library if it is not linked properly.

react-native link react-native-touch-id

Step 4 - 

After completing the installation and linking, now we need to add the app permissions to both android and iOS files.

  • Add this in the AndroidManifest.xml

<uses-permission android:name="android.permission.USE_FINGERPRINT"/>

  • Add this in the info.plist - 

<key>NSFaceIDUsageDescription</key>

<string>Enabling Face ID allows you quick access.</string>

Step 5 - 

This is a complete code for handling biometric functionality.

'use strict';

import React, { Component } from 'react';

import {

  AlertIOS,

  StyleSheet,

  Text,

  TouchableHighlight,

  View,

} from 'react-native';

import TouchID from "react-native-touch-id";

 

export default class FingerPrint extends Component<{}> {

  constructor() {

    super()

 

    this.state = {

      biometryType: null

    };

  }

 

  componentDidMount() {

    TouchID.isSupported()

    .then(biometryType => {

      this.setState({ biometryType });

    })

  }

 

  render() {

    return (

      <View style={styles.container}>

        <TouchableHighlight

          style={styles.btn}

          onPress={this.clickHandler}

          underlayColor="#0380BE"

          activeOpacity={1}

        >

          <Text style={{

            color: '#fff',

            fontWeight: '600'

          }}>

            {`Authenticate with ${this.state.biometryType}`}

          </Text>

        </TouchableHighlight>

      </View>

    );

  }

 

  clickHandler() {

    TouchID.isSupported()

      .then(authenticate)

      .catch(error => {

        AlertIOS.alert('TouchID not supported');

      });

  }

}

 

const styles = StyleSheet.create({

  container: {

    flex: 1,

    justifyContent: 'center',

    alignItems: 'center',

    backgroundColor: '#F5FCFF'

  },

  btn: {

    borderRadius: 3,

    marginTop: 200,

    paddingTop: 15,

    paddingBottom: 15,

    paddingLeft: 15,

    paddingRight: 15,

    backgroundColor: '#0391D7'

  }

});

 

function authenticate() {

  return TouchID.authenticate()

    .then(success => {

      AlertIOS.alert('Authenticated Successfully');

    })

    .catch(error => {

      console.log(error)

      AlertIOS.alert(error.message);

    });

}
So the blog is completed, I think you find it good to read then please like and share it, if you find any issue please comment.
 

Need a consultation?

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