Skip to main content

Integrate Touch ID and Face ID to your React Native App

Adding authentication using the user’s Touch ID or the new Face ID is easier than ever in your React Native App.
Using Touch ID also known as fingerprint authentication is extremely popular in mobile apps. The Touch ID feature secures the app and makes it a seamless authentication flow for the user.
Many banking apps like Bank of America, Discover, Chase, use Touch ID authentication enabling secure and seamless authentication.
The users don’t have to type the long passwords every time at login, by allowing them to login with their Touch ID.
With the iPhone X we have the provision to use Face ID authentication. Both Touch ID and Face ID authentication have improved the user’s interaction with mobile apps, making them secure.
In this post we are going to integrate Touch ID and Face ID authentication using the popular react-native-touch-id library.

Installation

Installation is fairly simple with the react-native-touch-id library.
If you are using yarn run the following command:
yarn add react-native-touch-id
If you are an npm user run the following command:
npm i --save react-native-touch-id
Make sure to link the library using the following command:
react-native link react-native-touch-id
After the installation is complete, we would need to add the app permissions to both android and iOS files.
In the AndroidManifest.xml add:
<uses-permission android:name="android.permission.USE_FINGERPRINT"/>
In the Info.plist add:
<key>NSFaceIDUsageDescription</key>
<string>Enabling Face ID allows you quick and secure access to your account.</string>
Once the above steps are complete, you are all set to start using the react-native-touch-id library within your app.

Usage

In the simple example below we are creating a component FingerPrint.js.
The function that is used for authenticating the user’s Touch ID is the authenticate(reason, config) function from the react-native-touch-id library.

TouchID.authenticate(reason, config)

This function authenticates with Touch ID or Face ID and returns a promise object. The reason is an optional string that is displayed to the user. It can provide information on why authentication is needed. The config is an optional object that can have more details to display in the dialog.

import React, { Component } from 'react';
import {
  AlertIOS,
  StyleSheet,
  Text,
  TouchableHighlight,
  View,
  NativeModules
} from 'react-native';

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

class FingerPrint extends React.Component {
 
  //config is optional to be passed in on Android
  const optionalConfigObject = {
   title: "Authentication Required", // Android
   color: "#e00606", // Android,
   fallbackLabel: "Show Passcode" // iOS (if empty, then label is hidden)
 }

  pressHandler() {
    TouchID.authenticate('to demo this react-native component', optionalConfigObject)
      .then(success => {
        AlertIOS.alert('Authenticated Successfully');
      })
      .catch(error => {
        AlertIOS.alert('Authentication Failed');
      });
  }
 
  render() {
    return (
      <View>
        <TouchableHighlight onPress={this.pressHandler}>
          <Text>
            Authenticate with Touch ID
          </Text>
        </TouchableHighlight>
      </View>
    );
  }
};
In the example above you can observe that the pressHandler() function handles the user’s Touch ID authentication using the TouchID.authentication() function. If the authentication does fail for some reason an error code is returned.
All of biometric authentication error codes are available in the official apple documentation:

TouchID.isSupported()

This function lets you know if biometric authentication is supported. It resolves to a string of TouchID or FaceID.
The example below shows usage of the isSupported() function.

  clickHandler() {
    TouchID.isSupported()
      .then(biometryType => {
        // Success code
        if (biometryType === 'FaceID') {
          console.log('FaceID is supported.');
        } else if (biometryType === 'TouchID'){
          console.log('TouchID is supported.');
        } else if (biometryType === true) {
         // Touch ID is supported on Android
 }
      })
      .catch(error => {
        // Failure code if the user's device does not have touchID or faceID enabled
        console.log(error);
      });
    }
The react-native-touch-id library supports use of Face ID for iPhone X devices. The isSupported() function returns the biometry type that is supported and enabled in the device. If the device does not support either Touch ID or Face ID then we will have to fallback to use of passwords or passcode.
Note here that the isSupported() function needs to be invoked before we call the authenticate() function. This ensures that we don’t authenticate using this library when biometric authentication is not available. A fallback authentication mechanism can be used in this case.

Putting it all together

The code below shows the cleaned up version of our authentication using react-native-touch-id. Notice here that we are saving the biometryType to the component’s state. We need to ensure to give the right message to the user on whether they are authenticating with the Touch ID or Face ID.

'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);
    });
}

Yay! You have now integrated the biometric authentication into your React Native application.
You can now explore the UI and different fallback options for your app when Touch ID or Face ID are not available on the user’s device.
Remember, when you are storing user passwords and sensitive information at login, you will have to store them in a secure keychain. The react-native-keychain library provides keychain access for React Native making your application secure.

Comments

Popular Posts

Master Map & Filter, Javascript’s Most Powerful Array Functions

Master Map & Filter, Javascript’s Most Powerful Array Functions Learn how Array.map and Array.filter work by writing them yourself This article is for those who have written a  for  loop before, but don’t quite understand how  Array.map  or  Array.filter  work. You should also be able to write a basic function. By the end of this, you’ll have a complete understanding of both functions, because you’ll have seen how they’re written. Array.map Array.map  is meant to transform one array into another by performing some operation on each of its values. The original array is left untouched and the function returns a new, transformed array. For example, say we have an array of numbers and we want to  multiply each number by three . We also don’t want to change the original array. To do this without  Array.map , we can use a standard for-loop. for-loop var originalArr = [1, 2, 3, 4, 5]; var newArr = []; for(var i = 0; i < originalArr.length; i+...

Integrate the FaceID or TouchID Authentication in iOS Apps - Swift

FaceID or TouchID Authentication Dear Folks, today I am going to explain the proper way to integrate the Face ID or Touch ID in iOS App. Face ID and Touch ID are secure, familiar authentication methods that people trust. Follow below steps: Step 1: Add NSFaceIDUsageDescription Key in info.plist file <key>NSFaceIDUsageDescription</key> <string>This app requires Face ID permission to authenticate using Face recognition.</string> Step 2: Create a swift file with any name but it would be better to related to its functionality, Like BioMetrixFile.swift Step 3: In BioMetrixFile write below codes and follow instructions. But before proceeding further import LocalAuthentication class in BioMetrixFile. Now, create typealias for success or failure blocks to well manage Authentication Success or Failure. public typealias AuthenticationSuccess = (() -> ()) public typealias AuthenticationFailure = ((AuthenticationError) -> ()) Now written all s...

React Native: How To Open App Settings Page

  React Native: How To Open App Settings Page React Native has a Linking module to manage the interaction with other applications in the device. In this article, I will explain how you can open “Application Setting Page” of the device using. Sample Case Before I explain how to do this, I’ll talk about an example case where we might need this: You need to get location permission within the application from a user using an iOS operating system and you asked for permission. But user did not agree to grant this permission the first time. In this case, you cannot ask your user for location permission the second time. In this case, the only thing to do is to direct the user to the settings page of our application and make it manually allow it. Now that we have explained our example situation, we can move on to how we can redirect our user to the “settings page of our application”. Open App Settings Page iOS If our user is using an iOS operating system, we can handle the whole process wit...