How to Implement Biometric Authentication in Android Apps

温柔守护 2022-10-06 ⋅ 14 阅读

Biometric authentication has gained popularity in recent years as a secure and convenient way to authenticate users in mobile applications. With Android's support for biometrics, developers can easily add biometric authentication to their apps using Kotlin or Java. In this blog post, we will explore how to implement biometric authentication in Android apps, covering both Kotlin and Java code examples.

Prerequisites

Before we begin, make sure you have the following prerequisites:

  1. Android Studio installed on your machine.
  2. An Android device or emulator with a fingerprint sensor.

1. Setting Up Permissions

To use biometric authentication in your Android app, you need to declare the necessary permissions in the app's manifest file. Add the following lines to your AndroidManifest.xml:

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

These permissions are required for accessing the fingerprint sensor and using biometrics in your app.

2. Adding Biometric Authentication to Your App

Kotlin Implementation

To implement biometric authentication in Kotlin, follow these steps:

  1. Create a new class for handling biometric authentication, for example, BiometricUtils.kt. Add the following code:
import android.content.Context
import android.hardware.biometrics.BiometricManager
import android.hardware.biometrics.BiometricPrompt
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.ContextCompat

class BiometricUtils(private val context: Context) {

    fun isBiometricSupported(): Boolean {
        val biometricManager = context.getSystemService(Context.BIOMETRIC_SERVICE) as BiometricManager
        return biometricManager.canAuthenticate() == BiometricManager.BIOMETRIC_SUCCESS
    }

    fun showBiometricPrompt(activity: AppCompatActivity, callback: BiometricPrompt.AuthenticationCallback) {
        val biometricPrompt = createBiometricPrompt(activity, callback)
        val promptInfo = createPromptInfo()
        biometricPrompt.authenticate(promptInfo)
    }

    private fun createBiometricPrompt(activity: AppCompatActivity, callback: BiometricPrompt.AuthenticationCallback): BiometricPrompt {
        return BiometricPrompt(activity, ContextCompat.getMainExecutor(activity), callback)
    }

    private fun createPromptInfo(): BiometricPrompt.PromptInfo {
        return BiometricPrompt.PromptInfo.Builder()
            .setTitle("Biometric authentication")
            .setSubtitle("Place your finger on the fingerprint sensor")
            .setNegativeButtonText("Cancel")
            .build()
    }
}
  1. In your activity, import the BiometricUtils class and add the following code where you want to trigger biometric authentication:
val utils = BiometricUtils(this)

if (utils.isBiometricSupported()) {
    val callback = object : BiometricPrompt.AuthenticationCallback() {
        override fun onAuthenticationSucceeded(result: BiometricPrompt.AuthenticationResult) {
            // Biometric authentication successful, proceed with app logic
        }

        override fun onAuthenticationError(errorCode: Int, errString: CharSequence) {
            super.onAuthenticationError(errorCode, errString)
            // Handle authentication error
        }

        override fun onAuthenticationFailed() {
            super.onAuthenticationFailed()
            // Handle authentication failure
        }
    }

    utils.showBiometricPrompt(this, callback)
} else {
    // Biometric authentication not supported
}

Java Implementation

To implement biometric authentication in Java, follow these steps:

  1. Create a new class for handling biometric authentication, for example, BiometricUtils.java. Add the following code:
import android.content.Context;
import android.hardware.biometrics.BiometricManager;
import android.hardware.biometrics.BiometricPrompt;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat;

public class BiometricUtils {

    private final Context context;

    public BiometricUtils(Context context) {
        this.context = context;
    }

    public boolean isBiometricSupported() {
        BiometricManager biometricManager = (BiometricManager) context.getSystemService(Context.BIOMETRIC_SERVICE);
        return biometricManager.canAuthenticate() == BiometricManager.BIOMETRIC_SUCCESS;
    }

    public void showBiometricPrompt(AppCompatActivity activity, BiometricPrompt.AuthenticationCallback callback) {
        BiometricPrompt biometricPrompt = createBiometricPrompt(activity, callback);
        BiometricPrompt.PromptInfo promptInfo = createPromptInfo();
        biometricPrompt.authenticate(promptInfo);
    }

    private BiometricPrompt createBiometricPrompt(AppCompatActivity activity, BiometricPrompt.AuthenticationCallback callback) {
        return new BiometricPrompt(activity, ContextCompat.getMainExecutor(activity), callback);
    }

    private BiometricPrompt.PromptInfo createPromptInfo() {
        return new BiometricPrompt.PromptInfo.Builder()
                .setTitle("Biometric authentication")
                .setSubtitle("Place your finger on the fingerprint sensor")
                .setNegativeButtonText("Cancel")
                .build();
    }
}
  1. In your activity, import the BiometricUtils class and add the following code where you want to trigger biometric authentication:
BiometricUtils utils = new BiometricUtils(this);

if (utils.isBiometricSupported()) {
    BiometricPrompt.AuthenticationCallback callback = new BiometricPrompt.AuthenticationCallback() {
        @Override
        public void onAuthenticationSucceeded(BiometricPrompt.AuthenticationResult result) {
            // Biometric authentication successful, proceed with app logic
        }

        @Override
        public void onAuthenticationError(int errorCode, CharSequence errString) {
            super.onAuthenticationError(errorCode, errString);
            // Handle authentication error
        }

        @Override
        public void onAuthenticationFailed() {
            super.onAuthenticationFailed();
            // Handle authentication failure
        }
    };

    utils.showBiometricPrompt(this, callback);
} else {
    // Biometric authentication not supported
}

Conclusion

By following the steps outlined in this blog post, you can easily implement biometric authentication in your Android apps using Kotlin or Java. Biometric authentication provides a secure and convenient way for users to authenticate, ensuring their data remains protected.


全部评论: 0

    我有话说: