Day 4: Adding Biometric Authentication (Face ID, Fingerprint)


#BiometricAuthentication #FaceID #FingerprintLogin

Welcome to Day 4 of Advanced Mobile App Security! Today, you’ll implement biometric authentication in your app to provide users with a secure and seamless login experience. By enabling Face ID or fingerprint login, you can enhance security while improving convenience.


What You’ll Learn Today

  1. Use biometric authentication in React Native.
  2. Integrate libraries for Face ID and fingerprint login.
  3. Handle secure fallback options if biometrics are unavailable.

Step 1: Install Biometric Authentication Library

Use react-native-biometrics for biometric authentication.

1. Install the Library

npm install react-native-biometrics
npx pod-install

2. Link the Library

For Android and iOS, ensure the native modules are properly linked. If you’re using React Native 0.60 or above, auto-linking should handle this.


Step 2: Configure Biometric Authentication

1. Setup Permissions

For Android:

  • Add the following permissions to AndroidManifest.xml:
<uses-permission android:name="android.permission.USE_BIOMETRIC" />
<uses-permission android:name="android.permission.USE_FINGERPRINT" />

For iOS:

  • Enable Face ID usage in your app’s Info.plist:
<key>NSFaceIDUsageDescription</key>
<string>We use Face ID for quick and secure login.</string>

Step 3: Implement Biometric Authentication

1. Create BiometricService

Create a file BiometricService.js:

import ReactNativeBiometrics from 'react-native-biometrics';

const rnBiometrics = new ReactNativeBiometrics();

export const isBiometricAvailable = async () => {
  const { available, biometryType } = await rnBiometrics.isSensorAvailable();
  if (available) {
    console.log(`Biometric type available: ${biometryType}`);
    return biometryType;
  } else {
    console.log('Biometric authentication is not available.');
    return null;
  }
};

export const authenticateWithBiometrics = async () => {
  try {
    const { success } = await rnBiometrics.simplePrompt({
      promptMessage: 'Confirm your identity',
    });
    if (success) {
      console.log('User authenticated successfully.');
      return true;
    } else {
      console.log('User authentication failed.');
      return false;
    }
  } catch (error) {
    console.error('Biometric authentication error:', error);
    return false;
  }
};

Step 4: Add Biometric Login to the App

1. Update AuthScreen

Enhance the AuthScreen.js to include biometric authentication:

import React, { useEffect, useState } from 'react';
import { View, Text, Button, StyleSheet } from 'react-native';
import { isBiometricAvailable, authenticateWithBiometrics } from './BiometricService';

const AuthScreen = ({ onLoginSuccess }) => {
  const [biometricType, setBiometricType] = useState(null);

  useEffect(() => {
    const checkBiometricAvailability = async () => {
      const type = await isBiometricAvailable();
      setBiometricType(type);
    };
    checkBiometricAvailability();
  }, []);

  const handleBiometricLogin = async () => {
    const isAuthenticated = await authenticateWithBiometrics();
    if (isAuthenticated) {
      onLoginSuccess({ name: 'Biometric User' });
    } else {
      alert('Biometric login failed.');
    }
  };

  return (
    <View style={styles.container}>
      <Text style={styles.title}>Login</Text>
      {biometricType && (
        <Button
          title={`Login with ${biometricType}`}
          onPress={handleBiometricLogin}
        />
      )}
    </View>
  );
};

const styles = StyleSheet.create({
  container: { flex: 1, justifyContent: 'center', alignItems: 'center' },
  title: { fontSize: 24, fontWeight: 'bold', marginBottom: 20 },
});

export default AuthScreen;

Step 5: Integrate Biometric Authentication into App.js

Update App.js to combine biometric and standard authentication methods:

import React, { useState } from 'react';
import { View, Text, StyleSheet } from 'react-native';
import AuthScreen from './AuthScreen';

const App = () => {
  const [user, setUser] = useState(null);

  return user ? (
    <View style={styles.container}>
      <Text style={styles.title}>Welcome, {user.name}!</Text>
    </View>
  ) : (
    <AuthScreen onLoginSuccess={(loggedInUser) => setUser(loggedInUser)} />
  );
};

const styles = StyleSheet.create({
  container: { flex: 1, justifyContent: 'center', alignItems: 'center' },
  title: { fontSize: 24, fontWeight: 'bold' },
});

export default App;

Step 6: Test Biometric Authentication

  1. Run the app: npx react-native run-android npx react-native run-ios
  2. Test Biometric Login:
    • On Android, test fingerprint authentication.
    • On iOS, test Face ID or Touch ID.
  3. Fallback Test:
    • Ensure the app handles scenarios where biometrics are unavailable (e.g., older devices).
See also  How to Deploy Locally Developed Laravel Projects to AWS: A Step-by-Step Guide

Enhance Biometric Authentication (Optional)

  1. Fallback to Password:
    • Allow users to fall back to email/password login if biometrics fail.
  2. MFA Integration:
    • Combine biometrics with multi-factor authentication (MFA) for enhanced security.
  3. Custom Prompts:
    • Customize the biometric prompt message for a better user experience.

SEO Optimization for This Tutorial

Keywords: Biometric authentication React Native, Face ID login, fingerprint login React Native, secure mobile app, React Native biometrics.

Meta Description: Learn how to implement biometric authentication in a React Native app. This tutorial covers Face ID, fingerprint login, and secure fallback options.


Summary

Today, you implemented biometric authentication, providing users with a secure and seamless way to log in using Face ID or fingerprints.

What’s Next: Tomorrow, you’ll learn to encrypt local storage for sensitive data.

Stay tuned for Day 5: Encrypting Local Storage.


Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.