How to integrate Biometric Authentication in Android App

Android Biometric Authentication offers a secure and convenient method for verifying user identity through fingerprints, facial recognition or iris scanning. This allows users to use the app without having to remember username and password every time they open the app. You can notice this in popular apps like Google Pay, PhonePe, WhatsApp and in few Banking apps.

Android biometric authentication fingerprint
Let's get started with some basics of biometric authentication.

1. Check the device support

Before using the biometric authentication, we need to check whether the device supports it or not. This can be done by calling canAuthenticate() method from BiometricManager. If this returns BIOMETRIC_SUCCESS, we can use the biometric authentication on the device.

Here we are using two types of authenticators
  1. BIOMETRIC_STRONG - Authenticate using any biometric method
  2. DEVICE_CREDENTIAL - Authenticate using device credentials like PIN, pattern or the password


const val AUTHENTICATORS = BIOMETRIC_STRONG or DEVICE_CREDENTIAL

fun canAuthenticate(context: Context) = BiometricManager.from(context)
        .canAuthenticate(AUTHENTICATORS) == BiometricManager.BIOMETRIC_SUCCESS

    

2. Enroll to Biometric Authentication

If canAuthenticate() returns BIOMETRIC_ERROR_NONE_ENROLLED, that means device supports it but user hasn't enorlled any biometric authentication method yet. To start the enroll process, we can start an Intent with Settings.ACTION_BIOMETRIC_ENROLL.

private val enrollBiometricRequestLauncher =
        registerForActivityResult(ActivityResultContracts.StartActivityForResult()) {
            if (it.resultCode == Activity.RESULT_OK) {
                // Biometric enrollment is successful. We can show the biometric login dialog
                showBiometricPrompt()
            } else {
                Log.e(
                    TAG,
                    "Failed to enroll in biometric authentication. Error code: ${it.resultCode}"
                )
            }
        }

fun isEnrolledPending(context: Context) = BiometricManager.from(context)
        .canAuthenticate(AUTHENTICATORS) == BiometricManager.BIOMETRIC_ERROR_NONE_ENROLLED
        
private fun enrollBiometric() {
        // Biometric is supported from Android 11 / Api level 30
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
            enrollBiometricRequestLauncher.launch(
                Intent(Settings.ACTION_BIOMETRIC_ENROLL).putExtra(
                    EXTRA_BIOMETRIC_AUTHENTICATORS_ALLOWED, BiometricUtils.AUTHENTICATORS
                )
            )
        }
    }

3. Showing the biometric login dialog

To show the biometric login dialog, we need to construct BiometricPrompt by passing list of authenticators we want to use using setAllowedAuthenticators() method.

val promptInfo = BiometricUtils.createPromptInfo(this)
        biometricPrompt.authenticate(promptInfo)

fun createPromptInfo(activity: AppCompatActivity): BiometricPrompt.PromptInfo =
        BiometricPrompt.PromptInfo.Builder().apply {
            setTitle(activity.getString(R.string.prompt_info_title))
            setSubtitle(activity.getString(R.string.prompt_info_subtitle))
            setAllowedAuthenticators(AUTHENTICATORS)
            setConfirmationRequired(false)
        }.build()
This will display the system's biometric dialog. You can customise the title, description displayed on this dialog.

4. Example App

As we have covered the basics, let's implement these in a simple app. In your Android Studio create a new project. While creating I have selected Bottom Navigation View Activity to have a working bottom navigation app.
  • This app will check for biometric support and will prompt the login only when the device supports it
  • It will start the enrollment process if user hasn't added any biometric or device credentials yet.
  • If the biometric authentication is enabled, it will display a non-dismissible dialog prompting users to unlock the app using biometric authentication. If the user denies it, the dialog will block the UI until user authenticates
  • Additionally, when app is kept in background for a certain duration (say 30 secs), the app will be locked and user has to authenticate again when the app is brought to foreground.
Android unlock app with biometric authentication
  1. Open app's build.gradle and add the biometric dependency.
    
    
    dependencies {
       ...
       implementation "androidx.biometric:biometric:1.2.0-alpha05"
       ...
    }
    
  2. Add the below strings to your strings.xml
  3. Create a new class file named BiometricUtils.kt and add the below code. In this object class, we define all the biometric related utility methods.
  4. Finally open the MainActivity and do the following changes.
    1. In onCreate(), if user hasn't added the biometric or device credentials, we start the enrollement of biometric authetication using showEnrollBiometricDialog() method
    2. In onResume(), showBiometricAuthIfNeeded() method is called to show the biometric login dialog if needed. This method checks few conditions like device support, the app's background state duration and displays the login prompt if app is kept in background for 30secs
    3. In onPause(), we store the timestamp when the app goes to background
    4. showLockedDialog() displays a non-dismissible dialog with Unlock option that triggers the biometric login prompt
If you run the app now, you should see the biometric authentication working in action. You can find the complete code here.

Cheers!
Happy Coding 🤗

3 Comments

  1. Awesome article! Clear steps and useful code for adding biometric authentication in Android apps. Thanks for sharing!

    ReplyDelete
Previous Post Next Post

نموذج الاتصال