Skip to content

Exploring the Capacitor Biometrics API

Modern mobile applications increasingly rely on biometric authentication to provide secure and convenient user experiences. With the Capacitor Biometrics plugin from Capawesome, developers can integrate powerful biometric authentication capabilities into their Ionic and Capacitor applications, enabling fingerprint, face, and iris recognition across Android, iOS, and Web platforms through a unified API that simplifies the complexity of platform-specific biometric implementations.

Installation

To install the Capacitor Biometrics plugin, please refer to the Installation section in the plugin documentation.

Usage

Let's explore the key features of the Capacitor Biometrics API and how to implement them in your Ionic applications.

Checking Availability

Before implementing biometric authentication, it's crucial to verify if biometric features are available on the device. The Capacitor Biometrics API provides the isAvailable(...) method for this purpose:

import { Biometrics } from '@capawesome-team/capacitor-biometrics';

const isAvailable = async () => {
  const result = await Biometrics.isAvailable();

  if (!result.isAvailable) {
    alert('Biometric authentication is not available on this device.');
    return;
  }
};

Make sure to call this method once before attempting any biometric operations. If no biometric features are available, you can gracefully handle the situation by informing the user or providing alternative authentication methods.

Checking Enrollment

Biometric authentication should not only but supported by the device, but also configured by the user. The isEnrolled(...) method allows you to check if the user has enrolled biometric data on their device:

const isEnrolled = async () => {
  const result = await Biometrics.isEnrolled();

  if (!result.isEnrolled) {
    alert('Please enroll biometric data in your device settings to use this feature.');
  }
};

If the user has not enrolled any biometric data, you can prompt them to do so through their device settings. On Android, you can even use the enroll(...) method to guide users through the enrollment process directly from your app:

import { Biometrics } from '@capawesome-team/capacitor-biometrics';

const enroll = async () => {
  await Biometrics.enroll();
};

This will open the device's biometric enrollment screen, allowing users to add their biometric data without leaving your application.

Authenticating with Biometrics

The core functionality of the plugin is provided through the authenticate(...) method, which triggers the biometric authentication process:

import { Biometrics, ErrorCode } from '@capawesome-team/capacitor-biometrics';

const authenticate = async () => {
  // If the user successfully authenticates, the promise resolves.
  // If the user cancels the authentication or if an error occurs, the promise rejects.
  try {
    await Biometrics.authenticate({
      title: 'Authentication Required',
      subtitle: 'Please authenticate to continue',
      cancelButtonText: 'Cancel',
      iosFallbackButtonText: 'Use Passcode',
    });
  } catch (error) {
    if (error.code === ErrorCode.USER_CANCELED) {
      console.log('User canceled the authentication.');
    } else if (error.code === ErrorCode.NOT_ENROLLED) {
      console.log('No biometric authentication enrolled.');
    } else if (error.code === ErrorCode.NOT_AVAILABLE) {
      console.log('Biometric authentication not available.');
    } else {
      console.log('Another error occurred:', error);
    }
  }
};

The authenticate(...) method accepts various configuration options to customize the authentication prompt, including titles, descriptions, and fallback options.

Make sure to handle the promise rejection properly to manage different error scenarios, such as user cancellation, biometric not enrolled, or biometric not available.

Authenticating with Device Credentials

In addition to biometric authentication, the Capacitor Biometrics API supports device credentials (PIN, pattern, or password) as a fallback option. You can enable this feature by setting the allowDeviceCredential option to true in the authenticate(...) method:

import { Biometrics, ErrorCode } from '@capawesome-team/capacitor-biometrics';

const authenticate = async () => {
  await Biometrics.authenticate({
    allowDeviceCredential: true,
  });
};

This allows users to authenticate using their device credentials if biometric recognition fails or is temporarily unavailable. It provides a seamless user experience by ensuring that authentication can still proceed even when biometrics are not an option.

Make sure to check if the device supports device credentials before enabling this option. You can do this using the hasDeviceCredential(...) method:

const checkDeviceCredential = async () => {
  const result = await Biometrics.hasDeviceCredential();

  if (result.hasDeviceCredential) {
    console.log('Device credential is available as fallback');
  } else {
    console.log('No device credential configured');
  }
};

If biometrics are not available and the user has not set up a device credential, this means that the device is completely unprotected. In this case, you may want to prohibit the use of your app on this device.

Canceling Authentication

For scenarios where you need to programmatically cancel an ongoing authentication process, use the cancelAuthentication(...) method:

const cancelAuth = async () => {
  await Biometrics.cancelAuthentication();
};

This method is useful when implementing custom UI flows or handling application state changes that require interrupting the authentication process.

Error Handling

Proper error handling is essential for a robust implementation. For this purpose, the Capacitor Biometrics API provides a set of error codes that help you identify specific issues during the authentication process. Here are some common error codes:

  • LOCKOUT: The device is locked out due to too many failed authentication attempts.
  • NOT_ENROLLED: The user has not enrolled any biometric data on the device.
  • SYSTEM_CANCELED: The system canceled the authentication process, typically due to a timeout or interruption.
  • TIMEOUT: The authentication process timed out before completion.
  • UNAVAILABLE: Biometric authentication is not available on the device.
  • USER_CANCELED: The user canceled the authentication process.

All error codes are defined in the ErrorCode enum, which you can import from the plugin:

import { ErrorCode } from '@capawesome-team/capacitor-biometrics';

Best Practices

When implementing biometric authentication with the Capacitor Biometrics API, consider these best practices:

  1. Check availability and enrollment: Always verify that biometrics are available and enrolled before presenting biometric options to users. Use isAvailable(...) and isEnrolled(...) to ensure the feature is ready for use.

  2. Provide fallback options: Enable device credential fallback using allowDeviceCredential: true in your authentication calls. This ensures users can still authenticate even if biometric recognition fails or is temporarily unavailable.

  3. Handle errors gracefully: Implement comprehensive error handling to manage different authentication scenarios. Provide clear feedback to users about authentication failures and guide them on alternative authentication methods.

  4. Customize authentication prompts: Use descriptive titles, subtitles, and descriptions in your authentication prompts to help users understand why authentication is required and what actions they can take.

  5. Respect user preferences: Allow users to disable biometric authentication in your app settings and provide alternative authentication methods for users who prefer not to use biometric features.

Conclusion

The Capacitor Biometrics Plugin from Capawesome provides a comprehensive solution for integrating biometric authentication into Ionic applications. By offering a unified API across multiple platforms, it enables developers to create secure and user-friendly authentication experiences without the complexity of platform-specific implementations.

To stay updated with the latest updates, features, and news about the Capawesome, Capacitor, and Ionic ecosystem, subscribe to the Capawesome newsletter and follow us on X (formerly Twitter).

If you have any questions or need assistance with the Capacitor Biometrics Plugin, feel free to reach out to the Capawesome team. We're here to help you implement secure biometric authentication in your Ionic applications.