DEV Community

NETIC
NETIC

Posted on • Updated on

Biometric Authentication in React Native App with Expo Local Authentication

We will setup authentication prompt for both Android and iOS using Expo Local Authentication. This is a quick snippet without the all noises but it should get you going, just add on to your codes.

As per document,

expo-local-authentication allows you to use the Biometric Prompt (Android) or FaceID and TouchID (iOS) to authenticate the user with a fingerprint or face scan.

Install package

npm install expo-local-authentication
## then
cd ios && pod install
Enter fullscreen mode Exit fullscreen mode

Add this to app.json (or app.config.json)

"plugins": [
  [
    "expo-local-authentication",
    {
      "faceIDPermission": "Allow $(PRODUCT_NAME) to use Face ID."
    }
  ]
],
Enter fullscreen mode Exit fullscreen mode

Add this to android/app/src/main/AndroidManifest.xml

<uses-permission android:name="android.permission.USE_BIOMETRIC" />
<uses-permission android:name="android.permission.USE_FINGERPRINT" />
Enter fullscreen mode Exit fullscreen mode

Add this to ios/Superpower/Info.plist

<key>NSFaceIDUsageDescription</key>
<string>Allow $(PRODUCT_NAME) to use FaceID</string>
Enter fullscreen mode Exit fullscreen mode

Create authenticator.ts

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

export const Authenthicator = {
  async unlock(): Promise<boolean> {
    const hasBiometric = await LocalAuthentication.hasHardwareAsync();
    if (!hasBiometric) {
      console.warn('Biometric authentication is not available on this device.');
      return false;
    }
    const result = await LocalAuthentication.authenticateAsync({
      promptMessage: 'Authenticate to access the app.',
      fallbackLabel: 'Use passcode instead?',
      disableDeviceFallback: true,
      cancelLabel: 'Cancel',
    });

    if (result.success) {
      console.log('Authenticated!');
      return true;
    }
    return false;
  },
};
Enter fullscreen mode Exit fullscreen mode

Now you can call Authenthicator.unlock() where you need biometric check. e.g Unlock Button onPress event.
The function returns true or false, then do your conditional things.

Top comments (0)