Skip to main content

Integrate Touch ID and Face ID to your React Native App

Integrate Touch ID and Face ID to your React Native App

Installation

Installation is fairly simple with the react-native-touch-id library.

yarn add react-native-touch-id
npm i --save react-native-touch-id
react-native link react-native-touch-id
<uses-permission android:name="android.permission.USE_FINGERPRINT"/>
<key>NSFaceIDUsageDescription</key>
<string>Enabling Face ID allows you quick and secure access to your account.</string>

Usage

In the simple example below we are creating a component FingerPrint.js.

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.

TouchID.isSupported()

This function lets you know if biometric authentication is supported. It resolves to a string of TouchID or FaceID.

  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.

Comments

Popular Posts

Reloading UITableView while Animating Scroll in iOS 11

Reloading UITableView while Animating Scroll Calling  reloadData  on  UITableView  may not be the most efficient way to update your cells, but sometimes it’s easier to ensure the data you are storing is in sync with what your  UITableView  is showing. In iOS 10  reloadData  could be called at any time and it would not affect the scrolling UI of  UITableView . However, in iOS 11 calling  reloadData  while your  UITableView  is animating scrolling causes the  UITableView  to stop its scroll animation and not complete. We noticed this is only true for scroll animations triggered via one of the  UITableView  methods (such as  scrollToRow(at:at:animated:) ) and not for scroll animations caused by user interaction. This can be an issue when server responses trigger a  reloadData  call since they can happen at any moment, possibly when scroll animation is occurring. Example of s...

What are the Alternatives of device UDID in iOS? - iOS7 / iOS 6 / iOS 5 – Get Device Unique Identifier UDID

Get Device Unique Identifier UDID Following code will help you to get the unique-device-identifier known as UDID. No matter what iOS user is using, you can get the UDID of the current iOS device by following code. - ( NSString *)UDID { NSString *uuidString = nil ; // get os version NSUInteger currentOSVersion = [[[[[UIDevice currentDevice ] systemVersion ] componentsSeparatedByString: @" . " ] objectAtIndex: 0 ] integerValue ]; if (currentOSVersion <= 5 ) { if ([[ NSUserDefaults standardUserDefaults ] valueForKey: @" udid " ]) { uuidString = [[ NSUserDefaults standardDefaults ] valueForKey: @" udid " ]; } else { CFUUIDRef uuidRef = CFUUIDCreate ( kCFAllocatorDefault ); uuidString = ( NSString *) CFBridgingRelease ( CFUUIDCreateString ( NULL ,uuidRef)); CFRelease (uuidRef); [[ NSUserDefaults standardUserDefaults ] setObject: uuidString ForKey: @" udid " ]; [[ NSUserDefaults standardUserDefaults ] synchro...

Xcode & Instruments: Measuring Launch time, CPU Usage, Memory Leaks, Energy Impact and Frame Rate

When you’re developing applications for modern mobile devices, it’s vital that you consider the performance footprint that it has on older devices and in less than ideal network conditions. Fortunately Apple provides several powerful tools that enable Engineers to measure, investigate and understand the different performance characteristics of an application running on an iOS device. Recently I spent some time with these tools working to better understand the performance characteristics of an eCommerce application and finding ways that we can optimise the experience for our users. We realised that applications that are increasingly performance intensive, consume excessive amounts of memory, drain battery life and feel uncomfortably slow are less likely to retain users. With the release of iOS 12.0 it’s easier than ever for users to find applications that are consuming the most of their device’s finite amount of resources. Users can now make informed decisions abou...