Mega Bundle Sale is ON! Get ALL of our React Native codebases at 95% OFF discount 🔥

React Native is one of the leading frameworks for developing cross-platform applications with ease. You can set up and get an app running in a couple of minutes due to its simple approach. Following React’s state-based rendering approach, applications built with React Native are very robust. In this article, we will be implementing React Native biometrics authentication with Expo, by leveraging expo-local-authentication open-source library. Let’s get started.

React Native Face ID Biometrics Auth

What Is Biometrics Authentication in React Native?

Biometrics authentication as the name suggests is a type of authentication that uses the physical human body characteristics to recognize the right user. We have seen it in the form of face identification, voice unlock, fingerprint unlock, iris scanning, etc. In this authentication scheme, the biometric data is stored locally on the device in encrypted form and hence, it is a lot secure. Data does not need to pass through severs which reduces the chances of it getting stolen. Biometric authentication is mostly used as an additional layer of security with pins and passwords.

How To Implement React Native Biometrics (Face ID and Touch ID) with Expo

Prerequisites

We require you to have a basic understanding of how does React Native and JavaScript work which will allow you to get around the implementation easily. Moreover, you must have an Android or an iOS device to run the application and test it. Lastly, node and npm should be installed on the local machine.

Setting Up the Project

As we are going to use expo for our biometrics authentication, let us install expo-cli using npm with the following command.

npm install -g expo-cli

After expo-cli is installed, enter the following command in the directory of your choice to initialize a new expo project.

expo init biometrics

This will set up our boilerplate and we can install the required dependencies for implementing the biometrics.

Installing Dependencies

For our local biometric authentication, we will be using expo-local-authentication which is a package for expo giving us API both for Android and IOS for biometrics. Install it with the following command.

expo install expo-localauthentication

With it installed, we are ready to dive deeper into the implementation!

Granting Permissions

On android, the permissions are automatically added once the library is installed while for IOS, you have to add the following key inside your info.plist file.

<key>NSFaceIDUsageDescription</key>
<string>$(PRODUCT_NAME) Authentication with TouchId or FaceID</string>

If for some reason, permissions fail to add on android, you can add the following lines in your AndroidManifest.xml file:

<uses-permission android:name=“android.permission.USE_BIOMETRIC” />
<uses-permission android:name=“android.permission.USE_FINGERPRINT” />

Using Biometrics for Face ID and Touch ID in a basic React Native app

To use the library, let us import in our App.js by putting the following line of code on the top.

The library provides us with a rich API around biometrics authentication. LocalAuthentication gives us a method called hasHardwareAsync which checks the device support for the authentication by returning us a boolean. For this specific tutorial, we are using an android phone with an in-built fingerprint scanner. To verify this via our application, enter the following code in App.js and save.

import { useState, useEffect } from “react”;
import { StyleSheet, Text, View, Alert } from “react-native”;
import * as LocalAuthentication from “expo-local-authentication”;

export default function App() {
  const [biometrics, setBiometrics] = useState(false);

  useEffect(() => {
    (async () => {
      const compatible = await LocalAuthentication.hasHardwareAsync();
      setBiometrics(compatible);
    })();
  });
  return (
    <View style={styles.container}>
      <Text>
     
        {biometrics
          ? “Your device is compatible with Biometrics”
          : “Face or Fingerprint scanner is available on this device”}
      </Text>
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: “#fff”,
    alignItems: “center”,
    justifyContent: “center”,
  },
});

The output for this can be seen as follows.

Now that we have verified that our device supports biometrics, let us create a secure component that will have secret information. This component will only be rendered after the user has been biometrically authenticated.

Note: Make sure you have registered your fingerprint or face ID in your device.

Let us create a new component named SecureFile.js and we add the following code inside it.

import { useState, useEffect } from “react”;
import { StyleSheet, Text, View, Alert } from “react-native”;
import * as LocalAuthentication from “expo-local-authentication”;

export default function SecureFile() {
  const [grantAccess, setGrantAccess] = useState(false);
  useEffect(() => {
    (async () => {
      const auth = await LocalAuthentication.authenticateAsync();
      if (auth.success) setGrantAccess(true);
      else setGrantAccess(false);
    })();
  }, []);
  return (
    <View style={styles.container}>
      {grantAccess && (
        <Text>this is the secret information: JSN#$@@@#NA*@!@#^^^??????</Text>
      )}
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    backgroundColor: “#fff”,
    alignItems: “center”,
    justifyContent: “center”,
  },
});

In this component, we are using authenticateAsync method given by the library which authenticates the user. It returns the response in object form after the promise has been resolved. 

We have a simple state that is set to false by default in order to keep the information hidden. It will only be set to true if the user is successfully authenticated with the biometrics. This logic has been implemeneted in the useEffect hook of the component. Now that we have our SecureFile component ready, let us move back to App.js and add a button that will render this component.

Our app.js looks as follows now.

import { useState, useEffect } from “react”;
import { StyleSheet, Text, View, Alert, Button } from “react-native”;
import * as LocalAuthentication from “expo-local-authentication”;
import SecureFile from “./SecureFile”;

export default function App() {
  const [biometrics, setBiometrics] = useState(false);
  const [renderContent, setRenderContent] = useState();

  useEffect(() => {
    (async () => {
      const compatible = await LocalAuthentication.hasHardwareAsync();
      setBiometrics(compatible);
    })();
  }, []);

  const renderSecureContent = () => setRenderContent(true);

  return (
    <View style={styles.container}>
      <Text>
        {biometrics
          ? “Your device is compatible with Biometrics”
          : “Face or Fingerprint scanner is available on this device”}
      </Text>
      {renderContent && <SecureFile />}
      <Button title=“Display Content” onPress={renderSecureContent} />
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: “#fff”,
    alignItems: “center”,
    justifyContent: “center”,
  },
});

Now that we have all of the pieces together, let us rebuild the project and see the results.

As we can see above, the user was able to authentication by fingerprint successfully and the secret content inside the SecureFile was displayed.

Conclusion

In this React Native tutorial, we have seen how to implement biometrics authentication with expo in React Native seamlessly. You can now add Face ID and Touch (fingerprint) ID authentication to any mobile app in just a few minutes. The exact same tutorial can be followed for iOS devices and you can either add authentication to your whole application or even to some specific screens. 

Categories: React Native

Leave a Reply

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

Shopping Cart