DEV Community

myougaTheAxo
myougaTheAxo

Posted on

Biometric Authentication in Android: Fingerprint and Face Recognition

Biometric authentication provides secure, convenient user authentication. Android's BiometricPrompt supports fingerprint and face recognition.

Basic Biometric Authentication

@Composable
fun BiometricLoginScreen(viewModel: AuthViewModel = viewModel()) {
    val context = LocalContext.current

    Button(
        onClick = {
            val biometricPrompt = BiometricPrompt(
                context as FragmentActivity,
                executor,
                object : BiometricPrompt.AuthenticationCallback() {
                    override fun onAuthenticationSucceeded(result: BiometricPrompt.AuthenticationResult) {
                        viewModel.onBiometricSuccess()
                    }

                    override fun onAuthenticationFailed() {
                        viewModel.onBiometricFailed()
                    }
                }
            )

            val promptInfo = BiometricPrompt.PromptInfo.Builder()
                .setTitle("Unlock App")
                .setSubtitle("Use your fingerprint")
                .setNegativeButtonText("Cancel")
                .build()

            biometricPrompt.authenticate(promptInfo)
        }
    ) {
        Text("Login with Fingerprint")
    }
}
Enter fullscreen mode Exit fullscreen mode

Using KeyStore with Biometric

Encrypt sensitive data using biometric authentication:

private fun createKeyWithBiometric() {
    val keyStore = KeyStore.getInstance("AndroidKeyStore")
    keyStore.load(null)

    val keyGenParameterSpec = KeyGenParameterSpec.Builder(
        "biometric_key",
        KeyProperties.PURPOSE_ENCRYPT or KeyProperties.PURPOSE_DECRYPT
    ).apply {
        setBlockModes(KeyProperties.BLOCK_MODE_CBC)
        setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_PKCS7)
        setUserAuthenticationRequired(true)
        setInvalidatedByBiometricEnrollment(true)
    }.build()

    KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, "AndroidKeyStore")
        .apply { init(keyGenParameterSpec) }
        .generateKey()
}
Enter fullscreen mode Exit fullscreen mode

Checking Biometric Availability

@Composable
fun CheckBiometricAvailability(context: Context) {
    val biometricManager = BiometricManager.from(context)

    when (biometricManager.canAuthenticate(BiometricManager.Authenticators.BIOMETRIC_STRONG)) {
        BiometricManager.BIOMETRIC_SUCCESS -> {
            Text("Biometric authentication available")
        }
        BiometricManager.BIOMETRIC_ERROR_NO_HARDWARE -> {
            Text("No biometric hardware available")
        }
        BiometricManager.BIOMETRIC_ERROR_HW_UNAVAILABLE -> {
            Text("Biometric hardware unavailable")
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Biometric authentication significantly improves security and user experience.


8 Android app templates available on Gumroad

Top comments (0)