Authentication flows and biometrics

Learn Android authentication: OAuth with PKCE via AppAuth and Custom Tabs, Credential Manager for passkeys and passwords, and BiometricPrompt with CryptoObject. About 25 minutes.

Why it matters

  • Sign-in code is where account takeovers start: an OAuth flow in a WebView, a missing PKCE check or a biometric "unlock" that is only a boolean flag are all real, recurring bugs.
  • Credential Manager is Android's current API for passkeys, saved passwords and Sign in with Google, replacing older Smart Lock and Google Sign-In APIs. Interviewers expect you to know what it covers and what it does not.
  • OAuth 2.0 and OpenID Connect on mobile have a specific best practice (RFC 8252): use the system browser through Custom Tabs, with PKCE. AppAuth implements it.
  • BiometricPrompt can be used with or without a CryptoObject. Knowing the difference, and which authenticator types to allow, is a common senior question.

The simple explanation

  • A building entrance. The badge office (identity provider) checks who you are and gives you a badge (tokens).
  • The guard at each door (your backend) checks the badge on every request.
  • The fingerprint reader on your desk drawer (BiometricPrompt) only protects what is already in the drawer, on this one phone.
  • If the drawer's lock is wired to a real key (a CryptoObject), forcing the reader's "OK" light on does not open it.

How does authentication work in an Android app? There are two separate jobs. Signing in proves the user's identity to your backend and produces tokens: use Credential Manager for passkeys, passwords and Sign in with Google, or OAuth 2.0 / OpenID Connect through AppAuth and Custom Tabs for other identity providers. Local re-authentication (unlocking the app, confirming a payment) uses BiometricPrompt, ideally tied to an Android Keystore key through a CryptoObject. The backend always makes the final decision by validating tokens or passkey signatures; the app never decides alone.

OAuth with PKCE. The app opens the provider's login page in a Custom Tab, not a WebView (a WebView lets the app see the user's password, and Google's sign-in pages refuse to load in one). The provider redirects back with a one-time authorization code, which the app exchanges for tokens. PKCE (Proof Key for Code Exchange, RFC 7636) protects that code: the app sends a hash of a random code_verifier with the request and the verifier itself with the exchange, so another app that intercepts the redirect cannot redeem the code. Mobile apps are public clients, so they must not hold a client secret.

Credential Manager (androidx.credentials) shows one system sheet for all saved credentials. You call getCredential with options such as GetPasswordOption, GetPublicKeyCredentialOption (passkeys, a WebAuthn JSON request from your server) and GetGoogleIdOption (Sign in with Google, from the googleid library). Your backend verifies what comes back: the passkey assertion or the Google ID token.

BiometricPrompt (androidx.biometric) has two modes:

ModeWhat success meansUse it for
Without CryptoObjectThe app's callback ranLow-risk convenience, such as hiding content until the user returns
With CryptoObjectA Keystore key that requires authentication was unlocked for this Cipher, Signature or MacDecrypting a stored token, signing a challenge for the server

Allowed authenticators are set with setAllowedAuthenticators: BIOMETRIC_STRONG (Class 3), BIOMETRIC_WEAK (Class 2) and DEVICE_CREDENTIAL (PIN, pattern, password). A CryptoObject requires BIOMETRIC_STRONG, optionally combined with DEVICE_CREDENTIAL on API 30+.

Login with OAuth and PKCE
Login with OAuth and PKCE The app creates a random code verifier and its S256 challenge. It opens the login page in a Custom Tab with the challenge. The user signs in at the authorization server, which redirects back to the app with an authorization code. The app exchanges the code together with the verifier for access and refresh tokens, and stores them in secure storage backed by the Keystore. A stolen code is useless without the verifier CREATE VERIFIER + S256 CHALLENGE OPEN LOGIN + CHALLENGE USER SIGNS IN REDIRECT WITH A CODE CODE + VERIFIER ACCESS + REFRESH TOKENS STORE THE TOKENS App your client Custom Tab browser Auth server authorization Secure storage Keystore-backed
Only the S256 challenge leaves the app at first; the secret verifier is sent only when exchanging the code, so a stolen code is useless.

Notes

  • Use Custom Tabs (through AppAuth) for OAuth, never a WebView. RFC 8252 recommends an external user agent for native apps.
  • AppAuth for Android (net.openid:appauth) creates the PKCE code_verifier and S256 code_challenge for you, handles the redirect and exchanges the code for tokens.
  • Never ship a client secret in the app; anything in the APK can be extracted. Register the app as a public client and rely on PKCE.
  • Credential Manager covers passkeys, passwords and Sign in with Google in one API. Generic OAuth to other identity providers still goes through AppAuth or the provider's SDK.
  • A passkey is a key pair kept by a credential provider such as Google Password Manager; your server stores only the public key and verifies a signature on each sign-in. It cannot be phished on a look-alike domain because it is bound to your domain.
  • Check BiometricManager.from(context).canAuthenticate(BIOMETRIC_STRONG) before offering biometric unlock. BIOMETRIC_ERROR_NONE_ENROLLED means the user has the hardware but no enrolled biometric.
  • For a key used with CryptoObject, set setUserAuthenticationRequired(true) and setUserAuthenticationParameters(0, KeyProperties.AUTH_BIOMETRIC_STRONG) (API 30+). A timeout of 0 means each operation needs its own prompt.
  • Biometric-bound keys are invalidated when a new biometric is enrolled, by default (setInvalidatedByBiometricEnrollment is true). Catch KeyPermanentlyInvalidatedException and send the user through full sign-in.
  • When DEVICE_CREDENTIAL is allowed, do not call setNegativeButtonText; the system shows the PIN option instead, and setting both throws.
  • Store tokens, not passwords. Keep access tokens short-lived and let the server rotate refresh tokens.

Code example

This class decrypts a stored refresh token only after a Class 3 biometric unlocks the Keystore key through a CryptoObject. It targets API 30+ for setUserAuthenticationParameters.

import android.security.keystore.KeyGenParameterSpec
import android.security.keystore.KeyPermanentlyInvalidatedException
import android.security.keystore.KeyProperties
import androidx.biometric.BiometricManager
import androidx.biometric.BiometricManager.Authenticators.BIOMETRIC_STRONG
import androidx.biometric.BiometricPrompt
import androidx.core.content.ContextCompat
import androidx.fragment.app.FragmentActivity
import java.security.GeneralSecurityException
import java.security.KeyStore
import javax.crypto.Cipher
import javax.crypto.KeyGenerator
import javax.crypto.SecretKey
import javax.crypto.spec.GCMParameterSpec
 
class BiometricTokenUnlock(private val activity: FragmentActivity) {
    private val alias = "biometric_token_key"
    private val keyStore = KeyStore.getInstance("AndroidKeyStore").apply { load(null) }
 
    fun canUseStrongBiometric(): Boolean =
        BiometricManager.from(activity).canAuthenticate(BIOMETRIC_STRONG) ==
            BiometricManager.BIOMETRIC_SUCCESS
 
    // Called when the token is first saved; the encrypt cipher also goes through the prompt.
    fun createKey(): SecretKey {
        val spec = KeyGenParameterSpec.Builder(
            alias,
            KeyProperties.PURPOSE_ENCRYPT or KeyProperties.PURPOSE_DECRYPT,
        )
            .setKeySize(256)
            .setBlockModes(KeyProperties.BLOCK_MODE_GCM)
            .setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_NONE)
            .setUserAuthenticationRequired(true)
            .setUserAuthenticationParameters(0, KeyProperties.AUTH_BIOMETRIC_STRONG)
            .setInvalidatedByBiometricEnrollment(true) // the default, stated for clarity
            .build()
        val generator = KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, "AndroidKeyStore")
        generator.init(spec)
        return generator.generateKey()
    }
 
    fun decryptToken(iv: ByteArray, ciphertext: ByteArray, onResult: (ByteArray?) -> Unit) {
        val key = keyStore.getKey(alias, null) as? SecretKey ?: return onResult(null)
        val cipher = Cipher.getInstance("AES/GCM/NoPadding")
        try {
            cipher.init(Cipher.DECRYPT_MODE, key, GCMParameterSpec(128, iv))
        } catch (e: KeyPermanentlyInvalidatedException) {
            keyStore.deleteEntry(alias) // new biometric enrolled: require full sign-in
            return onResult(null)
        }
 
        val callback = object : BiometricPrompt.AuthenticationCallback() {
            override fun onAuthenticationSucceeded(result: BiometricPrompt.AuthenticationResult) {
                val unlocked = result.cryptoObject?.cipher ?: return onResult(null)
                onResult(
                    try { unlocked.doFinal(ciphertext) } catch (e: GeneralSecurityException) { null }
                )
            }
 
            override fun onAuthenticationError(errorCode: Int, errString: CharSequence) {
                onResult(null) // cancelled, lockout or no hardware
            }
        }
 
        val promptInfo = BiometricPrompt.PromptInfo.Builder()
            .setTitle("Unlock your account")
            .setNegativeButtonText("Use password")
            .setAllowedAuthenticators(BIOMETRIC_STRONG)
            .build()
 
        BiometricPrompt(activity, ContextCompat.getMainExecutor(activity), callback)
            .authenticate(promptInfo, BiometricPrompt.CryptoObject(cipher))
    }
}
  • The Cipher is initialised before the prompt, but it can only doFinal after the user authenticates, because the key requires authentication for every use.
  • Success is proven by the unlocked Cipher returned in result.cryptoObject, not by the callback running. Hooking the callback without a real biometric gives an attacker a Cipher that still refuses to decrypt.
  • KeyPermanentlyInvalidatedException comes from Cipher.init; the recovery is to delete the key and fall back to a full sign-in.
  • For OAuth, AppAuth builds the request: AuthorizationRequest.Builder(serviceConfig, clientId, ResponseTypeValues.CODE, redirectUri).setScope("openid profile").build(), then AuthorizationService(context).getAuthorizationRequestIntent(request) opens a Custom Tab. PKCE is added by default.

Run the idea in plain Kotlin

This models PKCE with a fixed verifier so the output is deterministic. The "server" stores the S256 challenge with the code, and only a caller with the original verifier can redeem it.

import java.security.MessageDigest
import java.util.Base64

fun s256(verifier: String): String {
  val hash = MessageDigest.getInstance("SHA-256").digest(verifier.toByteArray(Charsets.US_ASCII))
  return Base64.getUrlEncoder().withoutPadding().encodeToString(hash)
}

class AuthServer {
  private val pending = mutableMapOf<String, String>() // code -> code_challenge

  fun authorize(codeChallenge: String): String {
      val code = "code-" + (pending.size + 1)
      pending[code] = codeChallenge
      return code
  }

  fun exchange(code: String, codeVerifier: String): String {
      val challenge = pending[code] ?: return "error: unknown or used code"
      if (s256(codeVerifier) != challenge) return "error: invalid_grant (verifier mismatch)"
      pending.remove(code) // codes are single use
      return "access token issued"
  }
}

fun main() {
  val server = AuthServer()

  // The app keeps the verifier in memory and sends only its hash
  val verifier = "dBjftJeZ4CVP-mJ92K9mGRBZ1kGEw0NeEg4NRZaDQ0"
  val challenge = s256(verifier)
  println("code_challenge = " + challenge)

  val code = server.authorize(challenge)
  println("Redirect delivered " + code)

  // Another app intercepted the redirect but never saw the verifier
  println("Attacker: " + server.exchange(code, "guessed-verifier"))
  println("App:      " + server.exchange(code, verifier))
  println("Replay:   " + server.exchange(code, verifier))
}

Expected output:

code_challenge = MeQrjttYbJSE3cZubEAsBwWLmJupr6-O0ZMpS1RAic0
Redirect delivered code-1
Attacker: error: invalid_grant (verifier mismatch)
App:      access token issued
Replay:   error: unknown or used code

In production

Biometric unlock bypassed with a hooking tool
  • An app's lock screen called BiometricPrompt without a CryptoObject and set isUnlocked = true in onAuthenticationSucceeded. The refresh token was stored with a key that did not require authentication.
  • During a penetration test, the tester used Frida on a rooted device to invoke the success callback directly and opened the app without a fingerprint.
  • Because the token could be decrypted without the user, the lock screen added no real protection for the data.
The fix
  • Re-encrypted the refresh token with a Keystore key created with setUserAuthenticationRequired(true) and AUTH_BIOMETRIC_STRONG.
  • Changed the unlock flow to pass a CryptoObject and decrypt the token with the Cipher returned in the result. A faked callback now yields a Cipher that cannot decrypt.
  • Handled KeyPermanentlyInvalidatedException by falling back to full sign-in.
OAuth login in a WebView with a client secret
  • An app embedded the identity provider's login page in a WebView and exchanged the code using a client secret stored in BuildConfig.
  • Users could not confirm they were on the real provider page, and the app could read every typed password. The client secret was readable from the APK.
  • The identity provider started rejecting embedded user agents, and login broke for part of the user base.
The fix
  • Moved the flow to AppAuth, which opens the login page in a Custom Tab and adds PKCE automatically.
  • Re-registered the app as a public client, rotated and removed the leaked secret, and redirected back to the app through a verified App Link.
  • Added Credential Manager with passkeys for the app's own accounts, so most users no longer type a password at all.

Common mistakes

  • Treating the biometric callback as proof. Without a CryptoObject, success is just a method call that can be hooked on a compromised device. Tie it to a Keystore key that requires authentication.
  • Running OAuth in a WebView. The app can see credentials, users cannot verify the page, and major providers block it. Use Custom Tabs through AppAuth.
  • Shipping a client secret. It is extractable from the APK. Mobile apps are public clients; use PKCE instead.
  • Allowing BIOMETRIC_WEAK for keys. Class 2 biometrics cannot unlock Keystore keys. Use BIOMETRIC_STRONG with a CryptoObject, optionally plus DEVICE_CREDENTIAL.
  • Ignoring key invalidation. A new fingerprint invalidates biometric-bound keys by default. Without handling KeyPermanentlyInvalidatedException, users are stuck.
  • Trusting tokens on the client. The backend must verify the Google ID token signature and audience, or the passkey assertion, itself. The app passing along "user is signed in" proves nothing.

Interview questions

Answer out loud first. Then reveal the answer and compare it at each depth.

“What is the difference between BiometricPrompt with and without a CryptoObject?”

“Explain the role of PKCE in OAuth 2.0 on mobile.”

“What does Credential Manager do, and what does it not do?”

“How would you design sign-in and biometric unlock for a banking app?”

Quiz

Which API should a modern Android app use to show a biometric authentication dialog?

Why should an Android app open OAuth login pages in a Custom Tab rather than a WebView?

A key is created with setUserAuthenticationRequired(true) and AUTH_BIOMETRIC_STRONG using the default settings. The user enrolls a new fingerprint. What happens?

What does PKCE protect against in a mobile OAuth flow?

0 of 4 answered

Mini task

Add biometric unlock backed by a Keystore key (25 min)

  1. In an app with min SDK 30, add androidx.biometric:biometric and host the flow in a FragmentActivity (AppCompatActivity extends it).
  2. Add the BiometricTokenUnlock class from the example. Show the unlock option only if canUseStrongBiometric() returns true.
  3. Write encryptToken(token: ByteArray, onResult: (iv: ByteArray, ciphertext: ByteArray) -> Unit): init a Cipher in ENCRYPT_MODE with the key, pass it through BiometricPrompt with a CryptoObject, and on success return cipher.iv and cipher.doFinal(token).
  4. Save the IV and ciphertext (Base64) in DataStore. On the next launch, call decryptToken and confirm the decrypted value matches.
  5. Enroll a new fingerprint in system settings, relaunch, and confirm the app deletes the key and falls back to full sign-in instead of crashing.

Done condition: the token can be decrypted only after a successful strong biometric, cancelling the prompt leaves it locked, and a new enrollment leads to a clean re-sign-in.

Next: Deep links and intent security