BiometricPrompt 的 KMM 封装?

解读

国内 Android 12+ 强制要求使用 BiometricPrompt 进行指纹/人脸认证,而 KMM(Kotlin Multiplatform Mobile)项目又必须把“生物识别”这一平台强相关能力下沉到 expect/actual 层。面试官问“怎么封装”,核心想看三点:

  1. 是否理解 BiometricPrompt 的异步流程与 CryptoObject 签名场景;
  2. 能否用 KMM 的 expect/actual 机制把 Android 侧 Jetpack Biometric 1.1.x 与 iOS 侧 LocalAuthentication 统一成一套协程 API;
  3. 是否考虑国内 ROM 兼容(华为、小米、OPPO 自定义指纹弹窗)、密钥强校验、降级方案与合规隐私提示。

一句话:不是让你讲 BiometricPrompt 用法,而是让你“设计一套 KMM 通用接口,让上层 common 模块一行代码调起生物识别,且 Android 侧真正走 BiometricPrompt”。

知识点

  • KMM expect/actual 编译期分发机制
  • AndroidX Biometric 1.1.x 新 API:BiometricPrompt.PromptInfo + setAllowedAuthenticators(DEVICE_CREDENTIAL or BIOMETRIC_STRONG)
  • 协程 CallbackFlow 把 Fragment/Activity 回调转成冷流
  • CryptoObject + Keystore 签名场景(支付级强校验)
  • iOS LocalAuthentication.LAContext、biometryType、LAPolicy.deviceOwnerAuthenticationWithBiometrics
  • 国内合规:隐私协议、用户明示同意、不可频繁弹窗、不可静默采集
  • 降级策略:无生物特征时走系统锁屏密码或自定义密码页
  • 多线程:BiometricPrompt 必须在主线程 show,但结果通过 Handler(Looper.getMainLooper()) 转回协程
  • 异常映射:Android 的 BiometricPrompt.ERROR_CANCELED、ERROR_LOCKOUT、ERROR_NO_BIOMETRICS 统一映射到 common 层密封类 BioException

答案

  1. commonMain 里声明 expect 接口
sealed interface BioResult {
    object Success : BioResult
    data class Failure(val code: Int, val msg: String) : BioResult
    object Cancelled : BioResult
    object Fallback : BioResult   // 用户点“使用密码”
}

expect class BiometricManager {
    suspend fun authenticate(
        title: String,
        subtitle: String = "",
        description: String = "",
        allowDeviceCredential: Boolean = true,
        crypto: BioCrypto? = null
    ): BioResult
}

@Serializable
data class BioCrypto(val keyAlias: String, val cipherPurpose: Int)
  1. androidMain 的 actual 实现
actual class BiometricManager actual constructor(
    private val activity: FragmentActivity   // 由 DI 注入
) {
    private val biometricPrompt = BiometricPrompt(
        activity,
        ContextCompat.getMainExecutor(activity),
        object : BiometricPrompt.AuthenticationCallback() {
            private val cont = CompletableDeferred<BioResult>()

            override fun onAuthenticationSucceeded(result: BiometricPrompt.AuthenticationResult) {
                cont.complete(BioResult.Success)
            }
            override fun onAuthenticationError(errorCode: Int, errString: CharSequence) {
                when (errorCode) {
                    BiometricPrompt.ERROR_CANCELED,
                    BiometricPrompt.ERROR_USER_CANCELED -> cont.complete(BioResult.Cancelled)
                    BiometricPrompt.ERROR_NEGATIVE_BUTTON -> cont.complete(BioResult.Fallback)
                    else -> cont.complete(BioResult.Failure(errorCode, errString.toString()))
                }
            }
            override fun onAuthenticationFailed() {
                // 单次识别失败,不结束流程,无需处理
            }

            suspend fun await() = cont.await()
        }
    )

    actual suspend fun authenticate(
        title: String,
        subtitle: String,
        description: String,
        allowDeviceCredential: Boolean,
        crypto: BioCrypto?
    ): BioResult = withContext(Dispatchers.Main) {
        val promptInfo = BiometricPrompt.PromptInfo.Builder()
            .setTitle(title)
            .setSubtitle(subtitle)
            .setDescription(description)
            .setAllowedAuthenticators(
                if (allowDeviceCredential) {
                    BIOMETRIC_STRONG or DEVICE_CREDENTIAL
                } else {
                    BIOMETRIC_STRONG
                }
            )
            .setNegativeButtonText("使用密码")   // 当 DEVICE_CREDENTIAL 未启用时才显示
            .build()

        val cryptoObject = crypto?.let { c ->
            val cipher = createCipher(c.keyAlias, c.cipherPurpose)
            BiometricPrompt.CryptoObject(cipher)
        }
        biometricPrompt.authenticate(promptInfo, cryptoObject)
        (biometricPrompt as? CompletableDeferred<BioResult>)?.await()
            ?: throw IllegalStateException("Callback not registered")
    }

    private fun createCipher(alias: String, purpose: Int): Cipher {
        val keyStore = KeyStore.getInstance("AndroidKeyStore").apply { load(null) }
        val key = keyStore.getKey(alias, null) as SecretKey
        return Cipher.getInstance("${key.algorithm}/ECB/PKCS7Padding").apply { init(purpose, key) }
    }
}
  1. iosMain 的 actual 实现
actual class BiometricManager {
    actual suspend fun authenticate(
        title: String,
        subtitle: String,
        description: String,
        allowDeviceCredential: Boolean,
        crypto: BioCrypto?
    ): BioResult = withContext(Dispatchers.Main) {
        val context = LAContext()
        context.localizedFallbackTitle = subtitle
        context.localizedCancelTitle = "取消"
        val policy = if (allowDeviceCredential) {
            LAPolicy.deviceOwnerAuthentication
        } else {
            LAPolicy.deviceOwnerAuthenticationWithBiometrics
        }
        val nsError = NSErrorPointer(null)
        return@withContext if (context.canEvaluatePolicy(policy, error = nsError)) {
            suspendCancellableCoroutine { cont ->
                context.evaluatePolicy(policy, localizedReason = description) { success, error ->
                    when {
                        success -> cont.resume(BioResult.Success)
                        error?.code == LAError.userCancel.toInt() -> cont.resume(BioResult.Cancelled)
                        error?.code == LAError.userFallback.toInt() -> cont.resume(BioResult.Fallback)
                        else -> cont.resume(BioResult.Failure(error?.code ?: -1, error?.localizedDescription ?: "Unknown"))
                    }
                }
            }
        } else {
            BioResult.Failure(nsError?.value?.code ?: -1, nsError?.value?.localizedDescription ?: "Biometry not available")
        }
    }
}
  1. 使用端(shared 模块 ViewModel)
class LoginViewModel : ViewModel() {
    private val bioManager: BiometricManager by inject()

    fun loginByFingerPrint() = viewModelScope.launch {
        when (val r = bioManager.authenticate("指纹登录", "请验证指纹", crypto = null)) {
            BioResult.Success -> repo.login()
            BioResult.Cancelled -> toast("用户取消")
            BioResult.Failure -> fallbackToPassword()
            else -> {}
        }
    }
}
  1. 国内合规补充
  • 在首次调用前弹隐私弹窗,告知“采集指纹仅用于本地验证,不上传服务器”;
  • 记录调用次数,防止 24h 内弹窗超过 3 次被应用商店下架;
  • 对华为 Mate60 等无 Google 服务机型,自动降级为 FingerprintManagerCompat(已废弃但可用)并提示用户;
  • 若 targetSdk >= 34,需在 Manifest 声明 USE_BIOMETRIC 与 USE_FINGERPRINT 双权限,避免小米商店审核失败。

拓展思考

  1. 如果业务要求“指纹+后端验签”双因子,如何把 CryptoObject 签名结果(byteArray)透传到 common 层,并让 iOS 侧也走 SecureEnclave 的 ECC 签名,实现算法一致性?
  2. 当用户关闭系统锁屏密码时,Android 14 会强制 ERROR_NO_DEVICE_CREDENTIAL,如何引导用户跳转到系统“安全与锁屏”页?
  3. KMM 在 iosArm64 与 iosSimulatorArm64 下 LocalAuthentication 行为差异(模拟器无 TouchID),如何用 Gradle 预编译宏跳过相关测试?
  4. 如果后续要扩展到 Compose Multiplatform for Desktop,Windows 的 Windows Hello 与 macOS 的 TouchID 如何再插拔到同一套 expect/actual 接口?