首页 > 解决方案 > BiometricPrompt.Authenticate() 不等待用户进行身份验证

问题描述

我正在尝试通过指纹为我的 Xamarin.Forms 移动应用程序实现用户身份验证,为此我正在使用 Android.Hardware.Biometrics 库。这是我用来实例化和显示提示的代码:

public bool Authenticate()
{
    // Create biometric prompt
    biometricPrompt = new BiometricPrompt.Builder(Android.App.Application.Context)
        .SetTitle("Authenticate")
        //this is most definitely wrong but just ignore this
        .SetNegativeButton("Cancel", Android.App.Application.Context.MainExecutor, new Android.App.DatePickerDialog(Android.App.Application.Context))
        .Build();
    BiometricAuthenticationCallback authCallback = new BiometricAuthenticationCallback();
    biometricPrompt.Authenticate(new CryptoObjectHelper().BuildCryptoObject(), new Android.OS.CancellationSignal(), Android.App.Application.Context.MainExecutor, authCallback);
    return authCallback.authSuccessful;
}

这是 BiometrcAuthenticationCallback 类:

class BiometricAuthenticationCallback : BiometricPrompt.AuthenticationCallback
{
    public bool authSuccessful = false;

    public override void OnAuthenticationSucceeded(BiometricPrompt.AuthenticationResult result)
    {
        authSuccessful = true;
    }
}

理想情况下,BiometricPrompt.Authenticate() 会停止代码执行,直到用户与指纹扫描仪交互,这样您就可以从 authCallback 读取结果,对吗?然而,情况并非如此......应用程序确实提示用户使用他的指纹进行身份验证,但应用程序只是继续运行,所以它会立即在下一行返回“false”......

我究竟做错了什么?在用户确认其身份之前,我是否应该自己停止代码执行?到目前为止我看到的所有代码示例都没有这样做......

标签: c#authenticationxamarin.androidfingerprint

解决方案


我认为您的功能逻辑public bool Authenticate()没有意义。

在你调用了下面的代码之后,为什么你会立即调用返回函数(return authCallback.authSuccessful;)?由于此时我们还没有使用指纹进行身份验证,因此代码return authCallback.authSuccessful;false立即返回。

BiometricAuthenticationCallback authCallback = new BiometricAuthenticationCallback();
biometricPrompt.Authenticate(new CryptoObjectHelper().BuildCryptoObject(), new Android.OS.CancellationSignal(), Android.App.Application.Context.MainExecutor, authCallback);

为此,您可以参考以下代码:

https://gist.github.com/justintoth/49484bb0c3a0494666442f3e4ea014c0


推荐阅读