react-native-fingerprint-scanner

repository·master·Indexed 21 days ago

https://github.com/hieuvp/react-native-fingerprint-scanner

A React Native library for authenticating users via fingerprint (TouchID) or FaceID on iOS and Android. It supports modern BiometricPrompt APIs on Android and legacy device-specific APIs for older versions. The library provides methods to check sensor availability via isSensorAvailable(), trigger authentication with authenticate(), and free resources using release().

Tokens
3.4K
Snippets
14
Records
18
Agent score
25%

What's inside react-native-fingerprint-scanner

  1. Configure App Permissions for Android and iOS

    master

    You must add the following permissions to your project files to enable biometric authentication.

    Android

    In AndroidManifest.xml:

    • API level 28+ (BiometricPrompt): <uses-permission android:name="android.permission.USE_BIOMETRIC" />
    • API level 23-28 (FingerprintCompat): <uses-permission android:name="android.permission.USE_FINGERPRINT" />
    • API level < 23 (Legacy Samsung/MeiZu - Deprecated in 4.0.0): <uses-permission android:name="android.permission.USE_FINGERPRINT" />

    iOS

    In Info.plist: Add a description for FaceID usage:

    <key>NSFaceIDUsageDescription</key>
    <string>$(PRODUCT_NAME) requires FaceID access to allows you quick and secure access.</string>
    <uses-permission android:name="android.permission.USE_BIOMETRIC" />
  2. Configure react-native-fingerprint-scanner manually

    master

    If automatic configuration fails, follow these manual steps:

    iOS

    1. In Xcode, right-click LibrariesAdd Files to [your project's name].
    2. Navigate to node_modules/react-native-fingerprint-scanner and add ReactNativeFingerprintScanner.xcodeproj.
    3. Link the library:
      • Select your project in the Xcode project navigator.
      • Go to the Build Phases tab.
      • Under Link Binary With Libraries, click the + button.
      • Search for libReactNativeFingerprintScanner.a and select it.
    4. Run your project (Cmd+R).

    Android

    1. Open android/app/src/main/java/[...]/MainApplication.java:
      • Add import com.hieuvp.fingerprint.ReactNativeFingerprintScannerPackage; to the imports.
      • Add new ReactNativeFingerprintScannerPackage() to the list returned by getPackages().
    2. Append to android/settings.gradle:
      include ':react-native-fingerprint-scanner'
      project(':react-native-fingerprint-scanner').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-fingerprint-scanner/android')
    3. Insert into android/app/build.gradle dependencies block:
      implementation project(':react-native-fingerprint-scanner')
    include ':react-native-fingerprint-scanner'
    project(':react-native-fingerprint-scanner').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-fingerprint-scanner/android')
  3. Configure Android build settings and Proguard

    master

    For full functionality (including FaceID on Android), ensure your android/app/build.gradle uses appropriate SDK versions:

    android {
        compileSdkVersion 29
        buildToolsVersion "29.0.2"
        defaultConfig {
            targetSdkVersion 29
        }
    }

    If using Proguard, add these rules to android/app/proguard-rules.pro (Note: Samsung and MeiZu rules are deprecated in 4.0.0):

    # MeiZu Fingerprint (Deprecated in 4.0.0)
    -keep class com.fingerprints.service.** { *; }
    -dontwarn com.fingerprints.service.**
    
    # Samsung Fingerprint (Deprecated in 4.0.0)
    -keep class com.samsung.android.sdk.** { *; }
    -dontwarn com.samsung.android.sdk.**
  4. Authenticate users on Android with authenticate()

    master

    On Android, use authenticate() to trigger the native biometric prompt.

    Options:

    • title (String): Title text for the native popup.
    • subTitle (String): Subtitle text for the native popup.
    • description (String): Description text for the native popup.
    • cancelButton (String): Text for the cancel button.
    • onAttempt (Function): A callback triggered when a user attempts a scan but fails.

    Returns: A Promise that resolves upon successful authentication or rejects on failure.

    FingerprintScanner
      .authenticate({ title: 'Log in with Biometrics' })
      .then(() => {
        this.props.onAuthenticate();
      });
  5. Check if biometric sensors are available with isSensorAvailable()

    master

    Use isSensorAvailable() to determine if the device supports biometric authentication and what type is currently available.

    • Returns: A Promise<string> resolving to the biometryType.
    • iOS values: 'Touch ID' or 'Face ID'.
    • Android values: 'Biometrics'.
    • Errors: If the check fails, the promise rejects with a FingerprintScannerError containing name, message, and biometric.
    FingerprintScanner
      .isSensorAvailable()
      .then(biometryType => this.setState({ biometryType }))
      .catch(error => this.setState({ errorMessage: error.message }));
  6. Authenticate users with FingerprintScanner.authenticate()

    master

    Use the authenticate method to trigger the biometric prompt. It accepts an options object and returns a Promise.

    iOS Usage:

    FingerprintScanner.authenticate({ description: 'Scan your fingerprint...' })
      .then(() => { /* success */ })
      .catch((error) => { /* error */ });

    Android Usage (Current API >= v23):

    FingerprintScanner.authenticate({ title: 'Log in with Biometrics' })
      .then(() => { /* success */ });

    Android Usage (Legacy API < v23): For older devices, you can use the onAttempt callback:

    FingerprintScanner.authenticate({ onAttempt: (error) => { /* handle attempt */ } })
      .then(() => { /* success */ })
      .catch((error) => { /* error */ });

    Important: Always call FingerprintScanner.release() when the component unmounts to free up resources.

    import FingerprintScanner from 'react-native-fingerprint-scanner';
    
    FingerprintScanner.authenticate({ title: 'Log in with Biometrics' })
      .then(() => {
        console.log('Authenticated successfully');
      })
      .catch((error) => {
        console.log(error.message);
      });
  7. Authenticate users on iOS with authenticate()

    master

    On iOS, use authenticate() to trigger the native biometric prompt.

    Options:

    • description (String): A message explaining to the user why authentication is being requested.
    • fallbackEnabled (Boolean): If true (default), allows the user to use a fallback method like entering their device passcode.

    Returns: A Promise that resolves upon successful authentication or rejects on failure.

    FingerprintScanner
      .authenticate({ description: 'Scan your fingerprint on the device scanner to continue' })
      .then(() => {
        this.props.handlePopupDismissed();
        AlertIOS.alert('Authenticated successfully');
      })
      .catch((error) => {
        this.props.handlePopupDismissed();
        AlertIOS.alert(error.message);
      });
  8. Release the fingerprint scanner with release()

    master

    Call release() to stop the fingerprint scanner listener, clear the internal state cache in native code, and cancel any visible native prompts. It is recommended to call this during the component unmount lifecycle to prevent memory leaks or hanging prompts.

    componentWillUnmount() {
      FingerprintScanner.release();
    }
  9. Reference: FingerprintScanner Error Codes

    master

    When a promise is rejected, the error object contains a name property corresponding to one of these error codes.

    | Name | Message |
    |---|---|
    | AuthenticationNotMatch | No match |
    | AuthenticationFailed | Authentication was not successful because the user failed to provide valid credentials |
    | AuthenticationTimeout | Authentication was not successful because the operation timed out |
    | AuthenticationProcessFailed | 'Sensor was unable to process the image. Please try again |
    | UserCancel | Authentication was canceled by the user - e.g. the user tapped Cancel in the dialog |
    | UserFallback | Authentication was canceled because the user tapped the fallback button (Enter Password) |
    | SystemCancel | Authentication was canceled by system - e.g. if another application came to foreground while the authentication dialog was up |
    | PasscodeNotSet | Authentication could not start because the passcode is not set on the device |
    | DeviceLocked | Authentication was not successful, the device currently in a lockout of 30 seconds |
    | DeviceLockedPermanent | Authentication was not successful, device must be unlocked via password |
    | DeviceOutOfMemory | Authentication could not proceed because there is not enough free memory on the device |
    | HardwareError | A hardware error occurred |
    | FingerprintScannerUnknownError | Could not authenticate for an unknown reason |
    | FingerprintScannerNotSupported | Device does not support Fingerprint Scanner |
    | FingerprintScannerNotEnrolled  | Authentication could not start because Fingerprint Scanner has no enrolled fingers |
    | FingerprintScannerNotAvailable | Authentication could not start because Fingerprint Scanner is not available on the device |