Bird
Raised Fist0
Android Kotlinmobile~15 mins

Biometric authentication in Android Kotlin - Deep Dive

Choose your learning style10 modes available
Overview - Biometric authentication
What is it?
Biometric authentication is a way for apps to recognize you using your unique body features like fingerprints or face. Instead of typing passwords, your phone checks these features to unlock apps or confirm your identity. It uses special sensors and software to do this safely and quickly. This makes logging in easier and more secure.
Why it matters
Without biometric authentication, people would rely only on passwords or PINs, which can be forgotten, stolen, or guessed. Biometrics make it faster and safer to access apps and services, reducing the risk of unauthorized access. This improves user experience and protects sensitive data, especially on mobile devices where typing long passwords is inconvenient.
Where it fits
Before learning biometric authentication, you should understand basic Android app development and permissions. After this, you can explore advanced security topics like encryption and multi-factor authentication. Biometric authentication fits into the security layer of mobile apps, helping protect user data and privacy.
Mental Model
Core Idea
Biometric authentication uses your unique physical traits as a secure key to prove who you are without typing passwords.
Think of it like...
It's like using your fingerprint to open a locked diary instead of remembering a secret code.
┌───────────────────────────────┐
│ User tries to access app       │
├───────────────────────────────┤
│ Device asks for biometric data │
├───────────────────────────────┤
│ User provides fingerprint/face │
├───────────────────────────────┤
│ System compares with stored    │
│ biometric template             │
├───────────────────────────────┤
│ If match → access granted      │
│ Else → access denied           │
└───────────────────────────────┘
Build-Up - 7 Steps
1
FoundationWhat is biometric authentication
🤔
Concept: Introduction to the idea of using body features for identity verification.
Biometric authentication means using parts of your body, like fingerprints or face shape, to prove who you are. Phones have sensors that can read these features and check if they match what was saved before. This replaces typing passwords.
Result
You understand that biometric authentication is a way to unlock or access apps using your body, not a password.
Knowing that biometrics are unique to each person helps you see why this method is secure and convenient.
2
FoundationTypes of biometric methods on Android
🤔
Concept: Learn the common biometric types supported on Android devices.
Android supports fingerprint scanning, face recognition, and iris scanning. Most phones have fingerprint sensors or front cameras for face recognition. Apps can use these methods if the device supports them and the user has set them up.
Result
You can identify which biometric methods your Android device can use for authentication.
Understanding device capabilities helps you design apps that use the right biometric method for the user.
3
IntermediateUsing BiometricPrompt API in Kotlin
🤔Before reading on: Do you think biometric authentication requires writing complex code or can it be done with simple Android APIs? Commit to your answer.
Concept: Learn how to use Android's BiometricPrompt API to request biometric authentication in apps.
Android provides BiometricPrompt, a simple API to show a system dialog asking for fingerprint or face. You create a BiometricPrompt object, set callbacks for success or failure, and then call authenticate(). This handles UI and security for you. Example: val biometricPrompt = BiometricPrompt(this, executor, callback) val promptInfo = BiometricPrompt.PromptInfo.Builder() .setTitle("Login") .setSubtitle("Use your fingerprint") .setNegativeButtonText("Cancel") .build() biometricPrompt.authenticate(promptInfo)
Result
You can add biometric login to your app with just a few lines of Kotlin code using BiometricPrompt.
Knowing that Android handles the complex parts lets you focus on app logic, making biometric integration easier and safer.
4
IntermediateHandling biometric authentication callbacks
🤔Before reading on: Do you think biometric success and failure are handled automatically or do you need to write code for them? Commit to your answer.
Concept: Understand how to respond to authentication results using callback methods.
When you call authenticate(), you provide a callback object with methods like onAuthenticationSucceeded and onAuthenticationFailed. You write code in these methods to decide what happens next, like opening the app or showing an error message.
Result
Your app reacts properly when the user succeeds or fails biometric authentication.
Handling callbacks correctly ensures a smooth user experience and proper security response.
5
IntermediateChecking device and user biometric readiness
🤔
Concept: Learn to verify if biometric hardware and user setup are available before asking for authentication.
Before showing biometric prompt, check if the device has biometric hardware and if the user has enrolled biometrics. Use BiometricManager: val biometricManager = BiometricManager.from(context) when (biometricManager.canAuthenticate()) { BiometricManager.BIOMETRIC_SUCCESS -> // ready BiometricManager.BIOMETRIC_ERROR_NO_HARDWARE -> // no sensor BiometricManager.BIOMETRIC_ERROR_NONE_ENROLLED -> // no biometrics set else -> // not available }
Result
Your app avoids errors by only asking for biometrics when possible and guides users to set them up if needed.
Checking readiness prevents crashes and improves user guidance.
6
AdvancedSecuring biometric data and fallback options
🤔Before reading on: Do you think biometric data is stored in your app or handled by the system? Commit to your answer.
Concept: Understand how biometric data is protected and how to provide fallback authentication methods.
Biometric data never leaves the device's secure hardware (like Trusted Execution Environment). Apps only get success or failure results, not raw data. You should also provide fallback options like PIN or password if biometrics fail or are unavailable. This ensures users can still access the app securely.
Result
Your app respects user privacy and remains accessible even if biometrics can't be used.
Knowing biometric data is protected by hardware builds trust and guides secure app design.
7
ExpertAdvanced biometric integration and edge cases
🤔Before reading on: Do you think biometric authentication always works the same on all devices? Commit to your answer.
Concept: Explore device differences, error handling, and combining biometrics with other security layers.
Different devices may support different biometrics or have varying sensor quality. Handle errors like sensor lockout after multiple failures. Combine biometrics with encrypted keys for stronger security. Also, consider user privacy laws and permissions carefully. Testing on many devices is crucial.
Result
Your app handles real-world biometric challenges gracefully and securely.
Understanding device variability and security layering prevents common production issues and strengthens app trust.
Under the Hood
Biometric authentication uses specialized hardware sensors to capture unique physical traits. These sensors convert the traits into encrypted templates stored securely in the device's Trusted Execution Environment or Secure Enclave. When authenticating, the sensor captures a new sample and compares it to the stored template inside this secure area. The app only receives a yes/no result, never the raw biometric data, ensuring privacy and security.
Why designed this way?
This design protects sensitive biometric data from exposure or theft by isolating it in secure hardware. It also standardizes biometric access through system APIs, so apps don't handle raw data or complex matching algorithms. Alternatives like storing biometrics in app storage were rejected due to high security risks and privacy concerns.
┌───────────────┐       ┌─────────────────────────────┐
│ Biometric     │       │ Secure Hardware (TEE/SE)    │
│ Sensor       ├──────▶│ Stores encrypted templates   │
└───────────────┘       │ Matches new samples internally│
                        └─────────────┬───────────────┘
                                      │
                                      ▼
                          ┌─────────────────────────┐
                          │ Android BiometricPrompt │
                          │ API returns success/fail│
                          └─────────────────────────┘
Myth Busters - 3 Common Misconceptions
Quick: Does biometric authentication send your fingerprint data to the app? Commit yes or no.
Common Belief:Apps receive and store your fingerprint or face data to verify you.
Tap to reveal reality
Reality:Apps never get raw biometric data; the system handles matching inside secure hardware and only tells apps if authentication succeeded or failed.
Why it matters:Believing apps get biometric data can cause privacy fears and misuse of biometric APIs, leading to insecure implementations.
Quick: Is biometric authentication always more secure than passwords? Commit yes or no.
Common Belief:Biometrics are always safer than passwords and can replace them completely.
Tap to reveal reality
Reality:Biometrics improve convenience and security but can be spoofed or fail. They should be combined with other security measures like PINs or encryption.
Why it matters:Overreliance on biometrics alone can lead to security gaps and lock users out if sensors fail.
Quick: Can biometric authentication work on any Android device? Commit yes or no.
Common Belief:All Android phones support biometric authentication the same way.
Tap to reveal reality
Reality:Support varies by device hardware and Android version; some devices lack sensors or user enrollment, so apps must check availability.
Why it matters:Assuming universal support causes app crashes or poor user experience on unsupported devices.
Expert Zone
1
Some devices use different biometric modalities simultaneously (face + fingerprint) and apps can choose which to prompt based on context.
2
BiometricPrompt supports cryptographic operations where successful authentication unlocks keys for encrypting data, adding a strong security layer.
3
Handling sensor lockout states and fallback authentication gracefully is critical for user retention and security compliance.
When NOT to use
Avoid biometric authentication in apps that require anonymous access or where user privacy laws restrict biometric data use. Instead, use strong passwords or hardware tokens. Also, do not rely solely on biometrics for high-security apps without multi-factor authentication.
Production Patterns
In production, apps combine BiometricPrompt with encrypted shared preferences or keystore keys. They check biometric availability at startup and guide users to enroll biometrics if missing. Apps handle errors like sensor lockout by falling back to PIN or password. Logging and analytics track biometric usage and failures to improve UX.
Connections
Encryption
Builds-on
Biometric authentication often unlocks encryption keys, linking identity verification directly to data protection.
User Experience Design
Builds-on
Smooth biometric flows improve app usability by reducing friction compared to passwords, showing how security and UX must work together.
Forensic Science
Similar pattern
Both biometric authentication and forensic science analyze unique physical traits to identify individuals, highlighting cross-domain use of pattern matching.
Common Pitfalls
#1Not checking if biometric hardware or enrollment is available before authentication.
Wrong approach:val biometricPrompt = BiometricPrompt(this, executor, callback) val promptInfo = BiometricPrompt.PromptInfo.Builder() .setTitle("Login") .build() biometricPrompt.authenticate(promptInfo)
Correct approach:val biometricManager = BiometricManager.from(context) if (biometricManager.canAuthenticate() == BiometricManager.BIOMETRIC_SUCCESS) { biometricPrompt.authenticate(promptInfo) } else { // Show fallback or enrollment prompt }
Root cause:Assuming biometric features are always present leads to app crashes or poor user experience.
#2Storing raw biometric data or templates in app storage.
Wrong approach:// Saving fingerprint data in SharedPreferences sharedPreferences.edit().putString("fingerprint", rawData).apply()
Correct approach:// Use BiometricPrompt API and system secure storage only // No raw data stored or accessed by app
Root cause:Misunderstanding security model and privacy risks causes unsafe handling of sensitive data.
#3Not providing fallback authentication when biometrics fail or are unavailable.
Wrong approach:Only calling biometricPrompt.authenticate() without alternative login methods.
Correct approach:If biometric fails or unavailable, show PIN/password login screen as fallback.
Root cause:Overreliance on biometrics ignores real-world failures and user needs.
Key Takeaways
Biometric authentication uses your unique body features to securely and conveniently verify identity without passwords.
Android's BiometricPrompt API simplifies adding biometric login by handling UI and security internally.
Biometric data is protected by secure hardware and never exposed to apps, ensuring privacy.
Always check device and user readiness before requesting biometric authentication to avoid errors.
Combine biometrics with fallback methods and encryption for robust, user-friendly security.

Practice

(1/5)
1. What is the main purpose of using BiometricPrompt in an Android app?
easy
A. To access the device camera for scanning QR codes
B. To create a custom login screen with username and password
C. To show the system biometric authentication dialog to the user
D. To manage network connections securely

Solution

  1. Step 1: Understand the role of BiometricPrompt

    BiometricPrompt is a system API that shows a standard biometric authentication dialog to the user.
  2. Step 2: Identify its main use

    It is used specifically for biometric authentication like fingerprint or face recognition, not for login screens or camera access.
  3. Final Answer:

    To show the system biometric authentication dialog to the user -> Option C
  4. Quick Check:

    BiometricPrompt = system biometric dialog [OK]
Hint: BiometricPrompt always shows system biometric dialog [OK]
Common Mistakes:
  • Confusing biometric prompt with custom login UI
  • Thinking it manages network or camera
  • Assuming it handles password input
2. Which of the following is the correct way to create a BiometricPrompt instance in Kotlin?
easy
A. val biometricPrompt = BiometricPrompt.create(this, executor, callback)
B. val biometricPrompt = BiometricPrompt(this, executor, callback)
C. val biometricPrompt = BiometricPrompt.newInstance(this, executor, callback)
D. val biometricPrompt = BiometricPrompt.Builder(this).build()

Solution

  1. Step 1: Recall BiometricPrompt constructor usage

    In Kotlin, BiometricPrompt is created by calling its constructor with context, executor, and callback.
  2. Step 2: Check each option

    Only val biometricPrompt = BiometricPrompt(this, executor, callback) uses the correct constructor syntax. Options A, C, and D use non-existent methods.
  3. Final Answer:

    val biometricPrompt = BiometricPrompt(this, executor, callback) -> Option B
  4. Quick Check:

    Constructor call = val biometricPrompt = BiometricPrompt(this, executor, callback) [OK]
Hint: Use constructor directly, no create() or newInstance() methods [OK]
Common Mistakes:
  • Using non-existent factory methods
  • Trying to use Builder pattern which BiometricPrompt doesn't have
  • Confusing with other Android APIs
3. Given this Kotlin code snippet, what will be printed if the user successfully authenticates biometrically?
val callback = object : BiometricPrompt.AuthenticationCallback() {
  override fun onAuthenticationSucceeded(result: BiometricPrompt.AuthenticationResult) {
    println("Success")
  }
  override fun onAuthenticationFailed() {
    println("Failed")
  }
}
// Assume biometricPrompt is initialized and authenticate() is called with this callback
medium
A. Failed
B. Error
C. Nothing
D. Success

Solution

  1. Step 1: Understand callback methods

    The onAuthenticationSucceeded method runs when biometric authentication is successful.
  2. Step 2: Identify printed output on success

    Inside onAuthenticationSucceeded, it prints "Success". So on success, "Success" is printed.
  3. Final Answer:

    Success -> Option D
  4. Quick Check:

    Success callback prints "Success" [OK]
Hint: Success callback prints "Success" exactly [OK]
Common Mistakes:
  • Confusing onAuthenticationFailed with success
  • Assuming error prints on success
  • Thinking no output occurs
4. What is wrong with this Kotlin code snippet for biometric authentication?
val biometricPrompt = BiometricPrompt(this, executor, callback)
biometricPrompt.authenticate(promptInfo)

// callback object missing override for onAuthenticationError
medium
A. It will work but won't handle errors properly
B. It will crash because onAuthenticationError is not overridden
C. It will not compile due to missing method
D. It will authenticate without any callback

Solution

  1. Step 1: Check callback completeness

    Overriding onAuthenticationError is recommended but not mandatory; missing it won't crash or prevent compilation.
  2. Step 2: Understand effect of missing error override

    Without onAuthenticationError, errors won't be handled gracefully, but authentication still runs.
  3. Final Answer:

    It will work but won't handle errors properly -> Option A
  4. Quick Check:

    Missing error override = no error handling [OK]
Hint: Missing error override causes no error handling, not crash [OK]
Common Mistakes:
  • Assuming missing override causes crash
  • Thinking code won't compile
  • Believing authentication runs without callback
5. You want to add biometric authentication to your app but only if the device supports it and the user has enrolled biometrics. Which Kotlin code snippet correctly checks these conditions before showing the prompt?
val biometricManager = BiometricManager.from(this)
val canAuthenticate = biometricManager.canAuthenticate(BiometricManager.Authenticators.BIOMETRIC_STRONG or BiometricManager.Authenticators.DEVICE_CREDENTIAL)
if (/* condition here */) {
  biometricPrompt.authenticate(promptInfo)
}
hard
A. canAuthenticate == BiometricManager.BIOMETRIC_SUCCESS
B. canAuthenticate != BiometricManager.BIOMETRIC_ERROR_NO_HARDWARE
C. canAuthenticate == BiometricManager.BIOMETRIC_ERROR_NONE_ENROLLED
D. canAuthenticate == BiometricManager.BIOMETRIC_ERROR_HW_UNAVAILABLE

Solution

  1. Step 1: Understand canAuthenticate return values

    canAuthenticate returns BIOMETRIC_SUCCESS if biometrics are available and enrolled.
  2. Step 2: Choose correct condition to proceed

    Only when canAuthenticate == BIOMETRIC_SUCCESS should the app show the biometric prompt.
  3. Final Answer:

    canAuthenticate == BiometricManager.BIOMETRIC_SUCCESS -> Option A
  4. Quick Check:

    Check for BIOMETRIC_SUCCESS before authenticating [OK]
Hint: Authenticate only if canAuthenticate equals BIOMETRIC_SUCCESS [OK]
Common Mistakes:
  • Checking for error codes instead of success
  • Ignoring enrollment status
  • Using wrong constants for condition
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard