项目作者: hieuvp

项目描述 :
Provide Fingerprint, Touch ID, and Face ID Scanner for React Native (Compatible with both Android and iOS)
高级语言: Java
项目地址: git://github.com/hieuvp/react-native-fingerprint-scanner.git
创建时间: 2017-06-02T08:46:10Z
项目社区:https://github.com/hieuvp/react-native-fingerprint-scanner

开源协议:

下载


React Native Fingerprint Scanner

Looking for Maintainers

This project is no longer actively maintained by the previous maintainers.
If you would like to propose a PR we can merge it though, it needs your effort to continue!


React Native Version
Version
NPM

React Native Fingerprint Scanner is a React Native library for authenticating users with Fingerprint (TouchID).

Table of Contents

iOS Version

The usage of the TouchID is based on a framework, named Local Authentication.

It provides a Default View that prompts the user to place a finger to the iPhone’s button for scanning.




Android Version

4.0.0 Prefers the new native Android BiometricPrompt lib on any Android >= v23 (M)
4.0.0 also DEPRECATES support for the legacy library that provides support for Samsung & MeiZu phones

3.0.2 and below:
Using an expandable Android Fingerprint API library, which combines Samsung and MeiZu‘s official Fingerprint API.

Samsung and MeiZu’s Fingerprint SDK supports most devices which system versions less than Android 6.0.




Installation

  1. $ npm install react-native-fingerprint-scanner --save

or

  1. $ yarn add react-native-fingerprint-scanner

Automatic Configuration

For RN >= 0.60

  1. $ cd ios && pod install

For RN < 0.60, use react-native link to add the library to your project:

  1. $ react-native link react-native-fingerprint-scanner

Manual Configuration

iOS

  1. In XCode, in the project navigator, right click LibrariesAdd Files to [your project's name]
  2. Go to node_modulesreact-native-fingerprint-scanner and add ReactNativeFingerprintScanner.xcodeproj
  3. To add the library “libReactNativeFingerprintScanner.a” to your project in XCode:
    • In the project navigator, select your project.
    • Click on the “Build Phases” tab.
    • Under “Link Binary With Libraries”, click the “+” button to add a new library.
    • Search for “libReactNativeFingerprintScanner.a” and select it.
    • Click “Add” to add the library to your project.
  4. Run your project (Cmd+R)

Android

  1. Open up android/app/src/main/java/[...]/MainApplication.java
    • Add import com.hieuvp.fingerprint.ReactNativeFingerprintScannerPackage; to the imports at the top of the file
    • Add new ReactNativeFingerprintScannerPackage() to the list returned by the getPackages() method
  2. Append the following lines to android/settings.gradle:
    1. include ':react-native-fingerprint-scanner'
    2. project(':react-native-fingerprint-scanner').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-fingerprint-scanner/android')
  3. Insert the following lines inside the dependencies block in android/app/build.gradle:
    1. implementation project(':react-native-fingerprint-scanner')

App Permissions

Add the following permissions to their respective files:

Android

In your AndroidManifest.xml:

API level 28+ (Uses Android native BiometricPrompt) (Reference)

  1. <uses-permission android:name="android.permission.USE_BIOMETRIC" ></uses-permission>

API level 23-28 (Uses Android native FingerprintCompat) Reference)

  1. <uses-permission android:name="android.permission.USE_FINGERPRINT" ></uses-permission>

// DEPRECATED in 4.0.0
API level <23 (Uses device-specific native fingerprinting, if available - Samsung & MeiZu only) Reference)

  1. <uses-permission android:name="android.permission.USE_FINGERPRINT" ></uses-permission>

iOS

In your Info.plist:

  1. <key>NSFaceIDUsageDescription</key>
  2. <string>$(PRODUCT_NAME) requires FaceID access to allows you quick and secure access.</string>

Extra Configuration

  1. Make sure the following versions are all correct in android/app/build.gradle

    1. // API v29 enables FaceId
    2. android {
    3. compileSdkVersion 29
    4. buildToolsVersion "29.0.2"
    5. ...
    6. defaultConfig {
    7. targetSdkVersion 29
  2. Add necessary rules to android/app/proguard-rules.pro if you are using proguard:

    1. # MeiZu Fingerprint
    2. // DEPRECATED in 4.0.0
    3. -keep class com.fingerprints.service.** { *; }
    4. -dontwarn com.fingerprints.service.**
    5. # Samsung Fingerprint
    6. // DEPRECATED in 4.0.0
    7. -keep class com.samsung.android.sdk.** { *; }
    8. -dontwarn com.samsung.android.sdk.**

Compatibility

  • For Gradle < 3 you MUST install react-native-fingerprint-scanner at version <= 2.5.0
  • For RN >= 0.57 and/or Gradle >= 3 you MUST install react-native-fingerprint-scanner at version >= 2.6.0
  • For RN >= 0.60 you MUST install react-native-fingerprint-scanner at version >= 3.0.0
  • For Android native Face Unlock, MUST use >= 4.0.0

Example

Example Source Code

iOS Implementation

  1. import React, { Component } from 'react';
  2. import PropTypes from 'prop-types';
  3. import { AlertIOS } from 'react-native';
  4. import FingerprintScanner from 'react-native-fingerprint-scanner';
  5. class FingerprintPopup extends Component {
  6. componentDidMount() {
  7. FingerprintScanner
  8. .authenticate({ description: 'Scan your fingerprint on the device scanner to continue' })
  9. .then(() => {
  10. this.props.handlePopupDismissed();
  11. AlertIOS.alert('Authenticated successfully');
  12. })
  13. .catch((error) => {
  14. this.props.handlePopupDismissed();
  15. AlertIOS.alert(error.message);
  16. });
  17. }
  18. render() {
  19. return false;
  20. }
  21. }
  22. FingerprintPopup.propTypes = {
  23. handlePopupDismissed: PropTypes.func.isRequired,
  24. };
  25. export default FingerprintPopup;

Android Implementation

  1. import React, { Component } from 'react';
  2. import PropTypes from 'prop-types';
  3. import {
  4. Alert,
  5. Image,
  6. Text,
  7. TouchableOpacity,
  8. View,
  9. ViewPropTypes,
  10. Platform,
  11. } from 'react-native';
  12. import FingerprintScanner from 'react-native-fingerprint-scanner';
  13. import styles from './FingerprintPopup.component.styles';
  14. import ShakingText from './ShakingText.component';
  15. // - this example component supports both the
  16. // legacy device-specific (Android < v23) and
  17. // current (Android >= 23) biometric APIs
  18. // - your lib and implementation may not need both
  19. class BiometricPopup extends Component {
  20. constructor(props) {
  21. super(props);
  22. this.state = {
  23. errorMessageLegacy: undefined,
  24. biometricLegacy: undefined
  25. };
  26. this.description = null;
  27. }
  28. componentDidMount() {
  29. if (this.requiresLegacyAuthentication()) {
  30. this.authLegacy();
  31. } else {
  32. this.authCurrent();
  33. }
  34. }
  35. componentWillUnmount = () => {
  36. FingerprintScanner.release();
  37. }
  38. requiresLegacyAuthentication() {
  39. return Platform.Version < 23;
  40. }
  41. authCurrent() {
  42. FingerprintScanner
  43. .authenticate({ title: 'Log in with Biometrics' })
  44. .then(() => {
  45. this.props.onAuthenticate();
  46. });
  47. }
  48. authLegacy() {
  49. FingerprintScanner
  50. .authenticate({ onAttempt: this.handleAuthenticationAttemptedLegacy })
  51. .then(() => {
  52. this.props.handlePopupDismissedLegacy();
  53. Alert.alert('Fingerprint Authentication', 'Authenticated successfully');
  54. })
  55. .catch((error) => {
  56. this.setState({ errorMessageLegacy: error.message, biometricLegacy: error.biometric });
  57. this.description.shake();
  58. });
  59. }
  60. handleAuthenticationAttemptedLegacy = (error) => {
  61. this.setState({ errorMessageLegacy: error.message });
  62. this.description.shake();
  63. };
  64. renderLegacy() {
  65. const { errorMessageLegacy, biometricLegacy } = this.state;
  66. const { style, handlePopupDismissedLegacy } = this.props;
  67. return (
  68. <View style={styles.container}>
  69. <View style={[styles.contentContainer, style]}>
  70. <Image
  71. style={styles.logo}
  72. source={require('./assets/finger_print.png')}
  73. ></Image>
  74. <Text style={styles.heading}>
  75. Biometric{'\n'}Authentication
  76. </Text>
  77. <ShakingText
  78. ref={(instance) => { this.description = instance; }}
  79. style={styles.description(!!errorMessageLegacy)}>
  80. {errorMessageLegacy || `Scan your ${biometricLegacy} on the\ndevice scanner to continue`}
  81. </ShakingText>
  82. <TouchableOpacity
  83. style={styles.buttonContainer}
  84. onPress={handlePopupDismissedLegacy}
  85. >
  86. <Text style={styles.buttonText}>
  87. BACK TO MAIN
  88. </Text>
  89. </TouchableOpacity>
  90. </View>
  91. </View>
  92. );
  93. }
  94. render = () => {
  95. if (this.requiresLegacyAuthentication()) {
  96. return this.renderLegacy();
  97. }
  98. // current API UI provided by native BiometricPrompt
  99. return null;
  100. }
  101. }
  102. BiometricPopup.propTypes = {
  103. onAuthenticate: PropTypes.func.isRequired,
  104. handlePopupDismissedLegacy: PropTypes.func,
  105. style: ViewPropTypes.style,
  106. };
  107. export default BiometricPopup;

API

isSensorAvailable(): (Android, iOS)

Checks if Fingerprint Scanner is able to be used by now.

  • Returns a Promise<string>
  • biometryType: String - The type of biometric authentication supported by the device.
    • iOS: biometryType = ‘Touch ID’, ‘Face ID’
    • Android: biometryType = ‘Biometrics’
  • error: FingerprintScannerError { name, message, biometric } - The name and message of failure and the biometric type in use.
  1. componentDidMount() {
  2. FingerprintScanner
  3. .isSensorAvailable()
  4. .then(biometryType => this.setState({ biometryType }))
  5. .catch(error => this.setState({ errorMessage: error.message }));
  6. }

authenticate({ description, fallbackEnabled }): (iOS)

Starts Fingerprint authentication on iOS.

  • Returns a Promise
  • description: String - the string to explain the request for user authentication.
  • fallbackEnabled: Boolean - default to true, whether to display fallback button (e.g. Enter Password).
  1. componentDidMount() {
  2. FingerprintScanner
  3. .authenticate({ description: 'Scan your fingerprint on the device scanner to continue' })
  4. .then(() => {
  5. this.props.handlePopupDismissed();
  6. AlertIOS.alert('Authenticated successfully');
  7. })
  8. .catch((error) => {
  9. this.props.handlePopupDismissed();
  10. AlertIOS.alert(error.message);
  11. });
  12. }

authenticate({ title="Log In", subTitle, description, cancelButton="Cancel", onAttempt=() => (null) }): (Android)

Starts Fingerprint authentication on Android.

  • Returns a Promise
  • title: String the title text to display in the native Android popup
  • subTitle: String the sub title text to display in the native Android popup
  • description: String the description text to display in the native Android popup
  • cancelButton: String the cancel button text to display in the native Android popup
  • onAttempt: Function - a callback function when users are trying to scan their fingerprint but failed.
  1. componentDidMount() {
  2. if (requiresLegacyAuthentication()) {
  3. authLegacy();
  4. } else {
  5. authCurrent();
  6. }
  7. }
  8. componentWillUnmount = () => {
  9. FingerprintScanner.release();
  10. }
  11. requiresLegacyAuthentication() {
  12. return Platform.Version < 23;
  13. }
  14. authCurrent() {
  15. FingerprintScanner
  16. .authenticate({ title: 'Log in with Biometrics' })
  17. .then(() => {
  18. this.props.onAuthenticate();
  19. });
  20. }
  21. authLegacy() {
  22. FingerprintScanner
  23. .authenticate({ onAttempt: this.handleAuthenticationAttemptedLegacy })
  24. .then(() => {
  25. this.props.handlePopupDismissedLegacy();
  26. Alert.alert('Fingerprint Authentication', 'Authenticated successfully');
  27. })
  28. .catch((error) => {
  29. this.setState({ errorMessageLegacy: error.message, biometricLegacy: error.biometric });
  30. this.description.shake();
  31. });
  32. }
  33. handleAuthenticationAttemptedLegacy = (error) => {
  34. this.setState({ errorMessageLegacy: error.message });
  35. this.description.shake();
  36. };

release(): (Android)

Stops fingerprint scanner listener, releases cache of internal state in native code, and cancels native prompt if visible.

  • Returns a Void
  1. componentWillUnmount() {
  2. FingerprintScanner.release();
  3. }

Types of Biometrics

Value OS Description
Touch ID iOS
Face ID iOS
Biometrics Android Refers to the biometric set as preferred on the device

Errors

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

License

MIT