Kotlin's Built-In Support for Biometric Authentication
Published: 2023-04-24 07:10:38

---
title: Kotlin's Built-In Support for Biometric Authentication
published: true
description:  This guide covered the fundamentals of implementing Authentication in Kotlin, including biometric Authentication.
tags: 
# cover_image: https://direct_url_to_image.jpg
# Use a ratio of 100:42 for best results.
# published_at: 2023-04-24 06:58 +0000
---
<img src="https://www.cmarix.com/blog/wp-content/uploads/2021/06/8-Killer-Kotlin-Tips-For-Android-App-Developers.png">
Using biometric authentication methods like facial or fingerprint scanning, you can protect your app's private information or paid content. Learn how to include biometric login flows into your app when you hire mobile app developers with the help of this tutorial. 
 
Users may save several fingerprints for future device unlocks and other scenarios when a <a href="https://www.cmarix.com/hire-kotlin-developers.html"><b>Hire Kotlin Developers</b></a> requires a biometric fingerprint. Using the Fingerprint Hardware Interface Definition Language, Android communicates with vendor-specific libraries and fingerprint hardware (such as a fingerprint sensor). Hire Kotlin Developers

 
<b>Let's Start:</b>
 
<h2><b>Step-by-Step Implementation</b></h2>
 
<h3><b>Step 1- Adding Dependency</d></3>
 
Implementation "android.biometric:biometric-ktx:1.2.0-alpha04"
 
<h3><b>step 2- Working with activity_main.xml</b></h3>
 
The ImageView now has a vector I placed in its drawable folder.
 
<?XML version="1.0" encoding="utf-8"?>
<androidx. Constraint layout. widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
  
xmlns:app="http://schemas.android.com/apk/res-auto"
   xmlns:tools="http://schemas.android.com/tools"
  
android:layout_width="match_parent"
  
android:layout_height="match_parent"
  
android:background="@color/purple_500"
   tools:context=".MainActivity">
 
   <ImageView
       android:id="@+id/imgFinger"
       android:layout_width="80dp"
       android:layout_height="80dp"
      
android:src="@drawable/ic_baseline_fingerprint_24"
      
app:layout_constraintBottom_toTopOf="@id/tvShowMsg"
      
app:layout_constraintEnd_toEndOf="parent"
       app:layout_constraintStart_toStartOf="parent"
      
app:layout_constraintTop_toTopOf="parent"
      
app:layout_constraintVertical_chainStyle="packed" />
 
   <TextView
       android:id="@+id/tvShowMsg"
      
android:layout_width="wrap_content"
       android:layout_height="wrap_content"
      
android:layout_marginVertical="25dp"
      
android:textColor="@color/white"
      
app:layout_constraintBottom_toTopOf="@id/button"
      
app:layout_constraintEnd_toEndOf="parent"
       app:layout_constraintStart_toStartOf="parent"
      
app:layout_constraintTop_toBottomOf="@id/imgFinger" />
 
 
   <Button
       android:id="@+id/button"
      
android:layout_width="wrap_content"
      
android:layout_height="wrap_content"
       android:text="Login"
       app:backgroundTint="#1A237E"
      
app:layout_constraintBottom_toBottomOf="parent"
      
app:layout_constraintEnd_toEndOf="parent"
      
app:layout_constraintStart_toStartOf="parent"
      
app:layout_constraintTop_toBottomOf="@id/tvShowMsg" />
</androidx.constraintlayout.widget.ConstraintLayout>
 
<h3><b>Step 3- Checking that biometric Authentication is available</b></h3>
 
fun checkDeviceHasBiometric() {
       val biometricManager = BiometricManager.from(this)
       when (biometricManager.canAuthenticate(BIOMETRIC_STRONG or DEVICE_CREDENTIAL)) {
           BiometricManager.BIOMETRIC_SUCCESS -> {
               Log.d("MY_APP_TAG", "App can authenticate using biometrics.")
               info = "App can authenticate using biometrics."
               binding. Button.isEnabled = true
 
           }
          
BiometricManager.BIOMETRIC_ERROR_NO_HARDWARE -> {
               Log.e("MY_APP_TAG", "No biometric features available on this device.")
               info = "No biometric features available on this device."
               binding. Button.isEnabled = false
 
           }
          
BiometricManager.BIOMETRIC_ERROR_HW_UNAVAILABLE -> {
               Log.e("MY_APP_TAG", "Biometric features are currently unavailable.")
               info = "Biometric features are currently unavailable."
               binding. Button.isEnabled = false
 
           }
          
BiometricManager.BIOMETRIC_ERROR_NONE_ENROLLED -> {
               // Prompts the user to create credentials that your app accepts.
               Val enrollment = Intent(Settings.ACTION_BIOMETRIC_ENROLL).apply {
                  
putExtra(Settings.EXTRA_BIOMETRIC_AUTHENTICATORS_ALLOWED,
                       BIOMETRIC_STRONG or DEVICE_CREDENTIAL)
               }
               binding. Button.isEnabled = false
 
              
startActivityForResult(enrollIntent, 100)
           }
       }
       binding.tvShowMsg.text = info
   }

<h3><b>Step 4 - Display the login prompt</b></h3>
 
You may utilize the Biometric library for the system to ask the user for biometric Authentication when you <a href="https://www.cmarix.com/hire-mobile-app-developers.html"><b>hire mobile app developers<b></a>. The user may have greater faith in the applications they use since this system-provided dialogue is the same across all of them for app ideas for beginners.
 
To implement this in your onCreate, use the following code:
 
override fun onCreate(savedInstanceState: Bundle?) {
       super.onCreate(savedInstanceState)
       binding = ActivityMainBinding.inflate(layoutInflater)
       setContentView(binding.root)
 
       binding. Button.isEnabled = false
       binding.imgFinger.setOnClickListener {
           checkDeviceHasBiometric()
       }
 
       executor = ContextCompat.getMainExecutor(this)
       biometricPrompt = BiometricPrompt(this, executor,
           object : BiometricPrompt.AuthenticationCallback() {
               override fun onAuthenticationError(
                   errorCode: Int,
                   errString: CharSequence,
               ) {
                  
super.onAuthenticationError(errorCode, errString)
                  
Toast.makeText(applicationContext,
                       "Authentication error: $errString", Toast.LENGTH_SHORT)
                       .show()
               }
 
               override fun onAuthenticationSucceeded(
                   result: BiometricPrompt.AuthenticationResult,
               ) {
                   super.onAuthenticationSucceeded(result)
                  
Toast.makeText(applicationContext,
                       "Authentication succeeded!", Toast.LENGTH_SHORT)
                       .show()
               }
 
               override fun onAuthenticationFailed() {
                  
super.onAuthenticationFailed()
                  
Toast.makeText(applicationContext, "Authentication failed",
                       Toast.LENGTH_SHORT)
                       .show()
               }
           })
 
       promptInfo = BiometricPrompt.PromptInfo.Builder()
           .setTitle("Biometric login for my app")
           .setSubtitle("Log in using your biometric credential")
           .setNegativeButtonText("Use account password")
           .build()
 
       // Prompt appears when the user clicks "Log in".
       // Consider integrating with the Keystore to unlock cryptographic operations,
       // if needed by your app.
 
       binding. Button.setOnClickListener {
          
biometricPrompt.authenticate(promptInfo)
       }
 
   }
 
<h2><b>The completed code for MainActivity.tk should look something like this:</b></h2>
 
class MainActivity : AppCompatActivity() {
   lateinit var binding: ActivityMainBinding
   lateinit var info: String
 
   private lateinit var executor: Executor
   private lateinit var biometricPrompt: BiometricPrompt
   private lateinit var promptInfo: BiometricPrompt.PromptInfo
 
  
//https://developer.android.com/training/sign-in/biometric-authl
 
   override fun onCreate(savedInstanceState: Bundle?) {
       super.onCreate(savedInstanceState)
       binding = ActivityMainBinding.inflate(layoutInflater)
       setContentView(binding.root)
 
       binding. Button.isEnabled = false
       binding.imgFinger.setOnClickListener {
           checkDeviceHasBiometric()
       }
 
       executor = ContextCompat.getMainExecutor(this)
       biometricPrompt = BiometricPrompt(this, executor,
           object : BiometricPrompt.AuthenticationCallback() {
               override fun onAuthenticationError(
                   errorCode: Int,
                   errString: CharSequence,
               ) {
                  
super.onAuthenticationError(errorCode, errString)
                   Toast.makeText(applicationContext,
                       "Authentication error: $errString", Toast.LENGTH_SHORT)
                       .show()
               }
 
               override fun onAuthenticationSucceeded(
                   result: BiometricPrompt.AuthenticationResult,
               ) {
                  
super.onAuthenticationSucceeded(result)
                  
Toast.makeText(applicationContext,
                       "Authentication succeeded!", Toast.LENGTH_SHORT)
                       .show()
               }
 
               override fun onAuthenticationFailed() {
                  
super.onAuthenticationFailed()
                  
Toast.makeText(applicationContext, "Authentication failed",
                       Toast.LENGTH_SHORT)
                       .show()
              
}
           })
 
       promptInfo = BiometricPrompt.PromptInfo.Builder()
           .setTitle("Biometric login for my app")
           .setSubtitle("Log in using your biometric credential")
           .setNegativeButtonText("Use account password")
           .build()
 
       // Prompt appears when user clicks "Log in".
       // Consider integrating with the Keystore to unlock cryptographic operations,
       // if needed by your app.
 
       binding. Button.setOnClickListener {
           biometricPrompt.authenticate(promptInfo)
       }
 
   }
 
   fun checkDeviceHasBiometric() {
       val biometricManager = BiometricManager.from(this)
       when (biometricManager.canAuthenticate(BIOMETRIC_STRONG or DEVICE_CREDENTIAL)) {
           BiometricManager.BIOMETRIC_SUCCESS -> {
               Log.d("MY_APP_TAG", "App can authenticate using biometrics.")
               info = "App can authenticate using biometrics."
               binding. Button.isEnabled = true
 
           }
          
BiometricManager.BIOMETRIC_ERROR_NO_HARDWARE -> {
               Log.e("MY_APP_TAG", "No biometric features available on this device.")
               info = "No biometric features available on this device."
               binding. Button.isEnabled = false
 
           }
          
BiometricManager.BIOMETRIC_ERROR_HW_UNAVAILABLE -> {
               Log.e("MY_APP_TAG", "Biometric features are currently unavailable.")
               info = "Biometric features are currently unavailable."
               binding. Button.isEnabled = false
 
           }
          
BiometricManager.BIOMETRIC_ERROR_NONE_ENROLLED -> {
               // Prompts the user to create credentials that your app accepts.
               Val enrollIntent = Intent(Settings.ACTION_BIOMETRIC_ENROLL).apply {
                  
putExtra(Settings.EXTRA_BIOMETRIC_AUTHENTICATORS_ALLOWED,
                       BIOMETRIC_STRONG or DEVICE_CREDENTIAL)
               }
               binding. Button.isEnabled = false
 
              
startActivityForResult(enrollIntent, 100)
           }
       }
       binding.tvShowMsg.text = info
   }
}
 
 
<h3><b>Conclusion</b></h3>
 
Any computer language that requires the assertion of a user's identity involves some Authentication for app ideas for beginners. This guide covered the fundamentals of implementing Authentication in Kotlin, including biometric Authentication.