نمایش کادر گفتگوی اصالت‌سنجی زیست‌سنجشی

یکی از روش‌های محافظت از اطلاعات حساس یا محتوای پولی در برنامه، درخواست اصالت‌سنجی زیست‌سنجشی است، مثل استفاده از تشخیص چهره یا تشخیص اثر انگشت. این راهنما توضیح می‌دهد که چگونه از جریان‌های ورود به سیستم زیست‌سنجشی در برنامه‌تان پشتیبانی کنید.

به‌عنوان یک قانون کلی، باید از Credential Manager برای ورود اولیه به سیستم در دستگاه استفاده کنید. صدور مجدد مجوزهای بعدی را می‌توان با Biometric Prompt یا Credential Manager انجام داد. مزیت استفاده از Biometric Prompt این است که گزینه‌های سفارشی‌سازی بیشتری ارائه می‌دهد، درحالی‌که Credential Manager یک پیاده‌سازی واحد را در هر دو جریان ارائه می‌دهد.

انواع اصالت‌سنجی‌ای را که برنامه‌تان پشتیبانی می‌کند اعلام کنید

برای تعریف انواع اصالت‌سنجی که برنامه‌تان پشتیبانی می‌کند، از میانای BiometricManager.Authenticators استفاده کنید. سیستم به شما امکان می‌دهد انواع زیر را برای اصالت‌سنجی اعلام کنید:

BIOMETRIC_STRONG
اصالت‌سنجی بااستفاده از داده‌های زیست‌سنجشی کلاس ۳، طبق تعریف ارائه‌شده در صفحه تعریف سازگاری Android.
BIOMETRIC_WEAK
اصالت‌سنجی بااستفاده از زیست‌سنجشی کلاس ۲، طبق تعریف ارائه‌شده در صفحه تعریف سازگاری Android.
DEVICE_CREDENTIAL
اصالت‌سنجی بااستفاده از اطلاعات اعتباری قفل صفحه – پین، الگو، یا گذرواژه کاربر.

برای شروع استفاده از اصالت‌سنج، کاربر باید پین، الگو، یا گذرواژه ایجاد کند. اگر کاربر ازقبل پین نداشته باشد، جریان ثبت‌نام زیست‌سنجشی از او می‌خواهد پین ایجاد کند.

برای تعریف انواع اصالت‌سنجی زیست‌سنجشی که برنامه‌تان می‌پذیرد، یک نوع اصالت‌سنجی یا ترکیب بیتی از انواع را به روش setAllowedAuthenticators() ارسال کنید. تکه‌کد زیر نحوه پشتیبانی از اصالت‌سنجی بااستفاده از زیست‌سنجشی «کلاس ۳» یا اطلاعات کاربری قفل صفحه را نشان می‌دهد.

کاتلین

// Lets the user authenticate using either a Class 3 biometric or
// their lock screen credential (PIN, pattern, or password).
promptInfo = BiometricPrompt.PromptInfo.Builder()
        .setTitle("Biometric login for my app")
        .setSubtitle("Log in using your biometric credential")
        .setAllowedAuthenticators(BIOMETRIC_STRONG or DEVICE_CREDENTIAL)
        .build()

جاوا

// Lets user authenticate using either a Class 3 biometric or
// their lock screen credential (PIN, pattern, or password).
promptInfo = new BiometricPrompt.PromptInfo.Builder()
        .setTitle("Biometric login for my app")
        .setSubtitle("Log in using your biometric credential")
        .setAllowedAuthenticators(BIOMETRIC_STRONG | DEVICE_CREDENTIAL)
        .build();

ترکیب‌های زیر از انواع اصالت‌سنج در Android 10 (سطح میانای برنامه‌سازی کاربردی ۲۹) و پایین‌تر پشتیبانی نمی‌شود: DEVICE_CREDENTIAL و BIOMETRIC_STRONG | DEVICE_CREDENTIAL. برای بررسی وجود پین، الگو، یا گذرواژه در Android نسخه ۱۰ و پایین‌تر، از روش KeyguardManager.isDeviceSecure() استفاده کنید.

بررسی کنید اصالت‌سنجی زیست‌سنجشی دردسترس باشد

پس‌از اینکه تصمیم گرفتید برنامه‌تان از کدام عناصر اصالت‌سنجی پشتیبانی کند، بررسی کنید که آیا این عناصر دردسترس هستند یا نه. برای انجام این کار، همان ترکیب بیتی از انواع را که بااستفاده از روش setAllowedAuthenticators() اعلام کرده‌اید به روش canAuthenticate() منتقل کنید. درصورت لزوم، کنش قصد ACTION_BIOMETRIC_ENROLL را فراخوانی کنید. در intent extra، مجموعه اصالت‌سنج‌هایی را که برنامه‌تان می‌پذیرد ارائه دهید. این هدف از کاربر می‌خواهد اطلاعات کاربری را برای اصالت‌سنجی که برنامه‌تان می‌پذیرد ثبت کند.

کاتلین

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.")
    BiometricManager.BIOMETRIC_ERROR_NO_HARDWARE ->
        Log.e("MY_APP_TAG", "No biometric features available on this device.")
    BiometricManager.BIOMETRIC_ERROR_HW_UNAVAILABLE ->
        Log.e("MY_APP_TAG", "Biometric features are currently unavailable.")
    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)
        }
        startActivityForResult(enrollIntent, REQUEST_CODE)
    }
}

جاوا

BiometricManager biometricManager = BiometricManager.from(this);
switch (biometricManager.canAuthenticate(BIOMETRIC_STRONG | DEVICE_CREDENTIAL)) {
    case BiometricManager.BIOMETRIC_SUCCESS:
        Log.d("MY_APP_TAG", "App can authenticate using biometrics.");
        break;
    case BiometricManager.BIOMETRIC_ERROR_NO_HARDWARE:
        Log.e("MY_APP_TAG", "No biometric features available on this device.");
        break;
    case BiometricManager.BIOMETRIC_ERROR_HW_UNAVAILABLE:
        Log.e("MY_APP_TAG", "Biometric features are currently unavailable.");
        break;
    case BiometricManager.BIOMETRIC_ERROR_NONE_ENROLLED:
        // Prompts the user to create credentials that your app accepts.
        final Intent enrollIntent = new Intent(Settings.ACTION_BIOMETRIC_ENROLL);
        enrollIntent.putExtra(Settings.EXTRA_BIOMETRIC_AUTHENTICATORS_ALLOWED,
                BIOMETRIC_STRONG | DEVICE_CREDENTIAL);
        startActivityForResult(enrollIntent, REQUEST_CODE);
        break;
}

تعیین نحوه اصالت‌سنجی کاربر

پس‌از اصالت‌سنجی کاربر، می‌توانید با فراخوانی getAuthenticationType() بررسی کنید که آیا کاربر بااستفاده از اطلاعات اعتباری دستگاه یا اطلاعات اعتباری زیست‌سنجشی اصالت‌سنجی شده است یا نه.

نمایش پیام ورود به سیستم

برای نمایش پیام‌واره سیستم که از کاربر درخواست می‌کند بااستفاده از اعتبارنامه‌های زیست‌سنجشی اصالت‌سنجی کند، از کتابخانه زیست‌سنجشی استفاده کنید. این کادر گفتگوی ارائه‌شده توسط سیستم در سراسر برنامه‌هایی که از آن استفاده می‌کنند یکسان است و تجربه کاربری قابل‌اعتمادتری ایجاد می‌کند. یک کادر گفتگوی نمونه در شکل ۱ نشان داده شده است.

نماگرفت کادر گفتگوی نمایش
شکل ۱. کادر گفتگوی سیستم که اصالت‌سنجی زیست‌سنجشی درخواست می‌کند.

برای افزودن اصالت‌سنجی زیست‌سنجشی به برنامه‌تان بااستفاده از کتابخانه «زیست‌سنجشی»، مراحل زیر را تکمیل کنید:

  1. در فایل build.gradle واحد برنامه‌تان، وابستگی به کتابخانه androidx.biometric را اضافه کنید.

  2. در فعالیت یا قطعه‌ای که میزبان کادر گفتگوی ورود به سیستم با اطلاعات زیست‌سنجشی است، کادر گفتگو را بااستفاده از منطق نشان‌داده‌شده در تکه‌کد زیر نمایش دهید:

    کاتلین

    private lateinit var executor: Executor
    private lateinit var biometricPrompt: BiometricPrompt
    private lateinit var promptInfo: BiometricPrompt.PromptInfo
    
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_login)
        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.
        val biometricLoginButton =
                findViewById<Button>(R.id.biometric_login)
        biometricLoginButton.setOnClickListener {
            biometricPrompt.authenticate(promptInfo)
        }
    }
    

    جاوا

    private Executor executor;
    private BiometricPrompt biometricPrompt;
    private BiometricPrompt.PromptInfo promptInfo;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        executor = ContextCompat.getMainExecutor(this);
        biometricPrompt = new BiometricPrompt(MainActivity.this,
                executor, new BiometricPrompt.AuthenticationCallback() {
            @Override
            public void onAuthenticationError(int errorCode,
                    @NonNull CharSequence errString) {
                super.onAuthenticationError(errorCode, errString);
                Toast.makeText(getApplicationContext(),
                    "Authentication error: " + errString, Toast.LENGTH_SHORT)
                    .show();
            }
    
            @Override
            public void onAuthenticationSucceeded(
                    @NonNull BiometricPrompt.AuthenticationResult result) {
                super.onAuthenticationSucceeded(result);
                Toast.makeText(getApplicationContext(),
                    "Authentication succeeded!", Toast.LENGTH_SHORT).show();
            }
    
            @Override
            public void onAuthenticationFailed() {
                super.onAuthenticationFailed();
                Toast.makeText(getApplicationContext(), "Authentication failed",
                    Toast.LENGTH_SHORT)
                    .show();
            }
        });
    
        promptInfo = new 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.
        Button biometricLoginButton = findViewById(R.id.biometric_login);
        biometricLoginButton.setOnClickListener(view -> {
                biometricPrompt.authenticate(promptInfo);
        });
    }
    

از راه‌حل رمزنگاری استفاده کنید که به اصالت‌سنجی وابسته است

برای محافظت بیشتر از اطلاعات حساس در برنامه‌تان، می‌توانید بااستفاده از نمونه‌ای از CryptoObject، رمزنگاری را در گردش کار اصالت‌سنجی زیست‌سنجشی‌تان ادغام کنید. این چارچوب از اشیای رمزنگاری زیر پشتیبانی می‌کند: Signature، Cipher، Mac، و KeyAgreement.

پس‌از اینکه کاربر بااستفاده از پیام‌واره زیست‌سنجشی با موفقیت اصالت‌سنجی شد، برنامه‌تان می‌تواند عملیات رمزنگاری انجام دهد. برای مثال، اگر بااستفاده از شیء Cipher اصالت‌سنجی کنید، برنامه‌تان می‌تواند بااستفاده از شیء SecretKey رمزگذاری و رمزگشایی کند.

بخش‌های زیر نمونه‌هایی از استفاده از شیء Cipher و شیء SecretKey برای رمزگذاری داده‌ها را نشان می‌دهند. هر مثال از روش‌های زیر استفاده می‌کند:

کاتلین

private fun generateSecretKey(keyGenParameterSpec: KeyGenParameterSpec) {
    val keyGenerator = KeyGenerator.getInstance(
            KeyProperties.KEY_ALGORITHM_AES, "AndroidKeyStore")
    keyGenerator.init(keyGenParameterSpec)
    keyGenerator.generateKey()
}

private fun getSecretKey(): SecretKey {
    val keyStore = KeyStore.getInstance("AndroidKeyStore")

    // Before the keystore can be accessed, it must be loaded.
    keyStore.load(null)
    return keyStore.getKey(KEY_NAME, null) as SecretKey
}

private fun getCipher(): Cipher {
    return Cipher.getInstance(KeyProperties.KEY_ALGORITHM_AES + "/"
            + KeyProperties.BLOCK_MODE_CBC + "/"
            + KeyProperties.ENCRYPTION_PADDING_PKCS7)
}

جاوا

private void generateSecretKey(KeyGenParameterSpec keyGenParameterSpec) {
    KeyGenerator keyGenerator = KeyGenerator.getInstance(
            KeyProperties.KEY_ALGORITHM_AES, "AndroidKeyStore");
    keyGenerator.init(keyGenParameterSpec);
    keyGenerator.generateKey();
}

private SecretKey getSecretKey() {
    KeyStore keyStore = KeyStore.getInstance("AndroidKeyStore");

    // Before the keystore can be accessed, it must be loaded.
    keyStore.load(null);
    return ((SecretKey)keyStore.getKey(KEY_NAME, null));
}

private Cipher getCipher() {
    return Cipher.getInstance(KeyProperties.KEY_ALGORITHM_AES + "/"
            + KeyProperties.BLOCK_MODE_CBC + "/"
            + KeyProperties.ENCRYPTION_PADDING_PKCS7);
}

اصالت‌سنجی فقط بااستفاده از اطلاعات اعتباری زیست‌سنجشی

اگر برنامه‌تان از کلید مخفی‌ای استفاده می‌کند که برای باز شدن قفل به اطلاعات اعتباری زیست‌سنجشی نیاز دارد، کاربر باید اطلاعات اعتباری زیست‌سنجشی خود را هر بار قبل‌از اینکه برنامه‌تان به کلید دسترسی پیدا کند اصالت‌سنجی کند.

برای رمزگذاری اطلاعات حساس فقط پس‌از اصالت‌سنجی کاربر بااستفاده از اعتبارنامه‌های زیست‌سنجشی، مراحل زیر را تکمیل کنید:

  1. کلیدی را بااستفاده از پیکربندی KeyGenParameterSpec زیر تولید کنید:

    کاتلین

    generateSecretKey(KeyGenParameterSpec.Builder(
            KEY_NAME,
            KeyProperties.PURPOSE_ENCRYPT or KeyProperties.PURPOSE_DECRYPT)
            .setBlockModes(KeyProperties.BLOCK_MODE_CBC)
            .setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_PKCS7)
            .setUserAuthenticationRequired(true)
            // Invalidate the keys if the user has registered a new biometric
            // credential, such as a new fingerprint. Can call this method only
            // on Android 7.0 (API level 24) or higher. The variable
            // "invalidatedByBiometricEnrollment" is true by default.
            .setInvalidatedByBiometricEnrollment(true)
            .build())
    

    جاوا

    generateSecretKey(new KeyGenParameterSpec.Builder(
            KEY_NAME,
            KeyProperties.PURPOSE_ENCRYPT | KeyProperties.PURPOSE_DECRYPT)
            .setBlockModes(KeyProperties.BLOCK_MODE_CBC)
            .setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_PKCS7)
            .setUserAuthenticationRequired(true)
            // Invalidate the keys if the user has registered a new biometric
            // credential, such as a new fingerprint. Can call this method only
            // on Android 7.0 (API level 24) or higher. The variable
            // "invalidatedByBiometricEnrollment" is true by default.
            .setInvalidatedByBiometricEnrollment(true)
            .build());
    
  2. گردش کار اصالت‌سنجی زیست‌سنجشی را که شامل رمز است شروع کنید:

    کاتلین

    biometricLoginButton.setOnClickListener {
        // Exceptions are unhandled within this snippet.
        val cipher = getCipher()
        val secretKey = getSecretKey()
        cipher.init(Cipher.ENCRYPT_MODE, secretKey)
        biometricPrompt.authenticate(promptInfo,
                BiometricPrompt.CryptoObject(cipher))
    }
    

    جاوا

    biometricLoginButton.setOnClickListener(view -> {
        // Exceptions are unhandled within this snippet.
        Cipher cipher = getCipher();
        SecretKey secretKey = getSecretKey();
        cipher.init(Cipher.ENCRYPT_MODE, secretKey);
        biometricPrompt.authenticate(promptInfo,
                new BiometricPrompt.CryptoObject(cipher));
    });
    
  3. در فراخوانی‌های اصالت‌سنجی زیست‌سنجشی، از کلید مخفی برای رمزگذاری اطلاعات حساس استفاده کنید:

    کاتلین

    override fun onAuthenticationSucceeded(
            result: BiometricPrompt.AuthenticationResult) {
        val encryptedInfo: ByteArray = result.cryptoObject.cipher?.doFinal(
            // plaintext-string text is whatever data the developer would like
            // to encrypt. It happens to be plain-text in this example, but it
            // can be anything
                plaintext-string.toByteArray(Charset.defaultCharset())
        )
        Log.d("MY_APP_TAG", "Encrypted information: " +
                Arrays.toString(encryptedInfo))
    }
    

    جاوا

    @Override
    public void onAuthenticationSucceeded(
            @NonNull BiometricPrompt.AuthenticationResult result) {
        // NullPointerException is unhandled; use Objects.requireNonNull().
        byte[] encryptedInfo = result.getCryptoObject().getCipher().doFinal(
            // plaintext-string text is whatever data the developer would like
            // to encrypt. It happens to be plain-text in this example, but it
            // can be anything
                plaintext-string.getBytes(Charset.defaultCharset()));
        Log.d("MY_APP_TAG", "Encrypted information: " +
                Arrays.toString(encryptedInfo));
    }
    

بااستفاده از اطلاعات کاربری زیست‌سنجشی یا صفحه قفل اصالت‌سنجی کنید

می‌توانید از کلید مخفی‌ای استفاده کنید که امکان اصالت‌سنجی بااستفاده از اعتبارنامه‌های زیست‌سنجشی یا اعتبارنامه‌های صفحه قفل (پین، الگو، یا گذرواژه) را فراهم می‌کند. هنگام پیکربندی این کلید، دوره زمانی اعتبار را مشخص کنید. درطول این دوره زمانی، برنامه شما می‌تواند چندین عملیات رمزنگاری را بدون نیاز به اصالت‌سنجی مجدد کاربر انجام دهد.

برای رمزگذاری اطلاعات حساس پس‌از اصالت‌سنجی کاربر بااستفاده از اطلاعات کاربری زیست‌سنجشی یا صفحه قفل، مراحل زیر را تکمیل کنید:

  1. کلیدی را بااستفاده از پیکربندی KeyGenParameterSpec زیر تولید کنید:

    کاتلین

    generateSecretKey(KeyGenParameterSpec.Builder(
            KEY_NAME,
            KeyProperties.PURPOSE_ENCRYPT or KeyProperties.PURPOSE_DECRYPT)
            .setBlockModes(KeyProperties.BLOCK_MODE_CBC)
            .setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_PKCS7)
            .setUserAuthenticationRequired(true)
            .setUserAuthenticationParameters(VALIDITY_DURATION_SECONDS,
                    ALLOWED_AUTHENTICATORS)
            .build())
    

    جاوا

    generateSecretKey(new KeyGenParameterSpec.Builder(
            KEY_NAME,
            KeyProperties.PURPOSE_ENCRYPT | KeyProperties.PURPOSE_DECRYPT)
            .setBlockModes(KeyProperties.BLOCK_MODE_CBC)
            .setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_PKCS7)
            .setUserAuthenticationRequired(true)
            .setUserAuthenticationParameters(VALIDITY_DURATION_SECONDS,
                    ALLOWED_AUTHENTICATORS)
            .build());
    
  2. در بازه زمانی VALIDITY_DURATION_SECONDS پس‌از اصالت‌سنجی کاربر، اطلاعات حساس را رمزگذاری کنید:

    کاتلین

    private fun encryptSecretInformation() {
        // Exceptions are unhandled for getCipher() and getSecretKey().
        val cipher = getCipher()
        val secretKey = getSecretKey()
        try {
            cipher.init(Cipher.ENCRYPT_MODE, secretKey)
            val encryptedInfo: ByteArray = cipher.doFinal(
                // plaintext-string text is whatever data the developer would
                // like to encrypt. It happens to be plain-text in this example,
                // but it can be anything
                    plaintext-string.toByteArray(Charset.defaultCharset()))
            Log.d("MY_APP_TAG", "Encrypted information: " +
                    Arrays.toString(encryptedInfo))
        } catch (e: InvalidKeyException) {
            Log.e("MY_APP_TAG", "Key is invalid.")
        } catch (e: UserNotAuthenticatedException) {
            Log.d("MY_APP_TAG", "The key's validity timed out.")
            biometricPrompt.authenticate(promptInfo)
        }
    

    جاوا

    private void encryptSecretInformation() {
        // Exceptions are unhandled for getCipher() and getSecretKey().
        Cipher cipher = getCipher();
        SecretKey secretKey = getSecretKey();
        try {
            // NullPointerException is unhandled; use Objects.requireNonNull().
            ciper.init(Cipher.ENCRYPT_MODE, secretKey);
            byte[] encryptedInfo = cipher.doFinal(
                // plaintext-string text is whatever data the developer would
                // like to encrypt. It happens to be plain-text in this example,
                // but it can be anything
                    plaintext-string.getBytes(Charset.defaultCharset()));
        } catch (InvalidKeyException e) {
            Log.e("MY_APP_TAG", "Key is invalid.");
        } catch (UserNotAuthenticatedException e) {
            Log.d("MY_APP_TAG", "The key's validity timed out.");
            biometricPrompt.authenticate(promptInfo);
        }
    }
    

اصالت‌سنجی بااستفاده از کلیدهای «اصالت‌سنجی برای هر استفاده»

می‌توانید برای کلیدهای «احراز هویت برای هر استفاده» در نمونه BiometricPrompt خود پشتیبانی ارائه دهید. چنین کلیدی از کاربر می‌خواهد که هربار برنامه‌تان نیاز به دسترسی به داده‌های محافظت‌شده توسط آن کلید دارد، اعتبارنامه زیست‌سنجشی یا اعتبارنامه دستگاه ارائه دهد. کلیدهای «احراز هویت برای هر استفاده» می‌تواند برای تراکنش‌های باارزش بالا مفید باشد، مثلاً انجام پرداخت‌های بزرگ یا به‌روزرسانی سوابق سلامتی افراد.

برای مرتبط کردن شیء BiometricPrompt با کلید «احراز هویت برای هر استفاده»، کدی مشابه کد زیر اضافه کنید:

کاتلین

val authPerOpKeyGenParameterSpec =
        KeyGenParameterSpec.Builder("myKeystoreAlias", key-purpose)
    // Accept either a biometric credential or a device credential.
    // To accept only one type of credential, include only that type as the
    // second argument.
    .setUserAuthenticationParameters(0 /* duration */,
            KeyProperties.AUTH_BIOMETRIC_STRONG or
            KeyProperties.AUTH_DEVICE_CREDENTIAL)
    .build()

جاوا

KeyGenParameterSpec authPerOpKeyGenParameterSpec =
        new KeyGenParameterSpec.Builder("myKeystoreAlias", key-purpose)
    // Accept either a biometric credential or a device credential.
    // To accept only one type of credential, include only that type as the
    // second argument.
    .setUserAuthenticationParameters(0 /* duration */,
            KeyProperties.AUTH_BIOMETRIC_STRONG |
            KeyProperties.AUTH_DEVICE_CREDENTIAL)
    .build();

اصالت‌سنجی بدون کنش صریح کاربر

به‌طور پیش‌فرض، سیستم از کاربران می‌خواهد پس‌از پذیرفته شدن اطلاعات اعتباری زیست‌سنجشی‌شان، کنش خاصی را انجام دهند، مثلاً دکمه‌ای را فشار دهند. اگر برنامه‌تان کادر گفتگویی را برای تأیید کنشی حساس یا پرخطر (مثل خرید کردن) نشان می‌دهد، این پیکربندی ترجیح داده می‌شود.

اما اگر برنامه‌تان برای کنشی با ریسک کمتر، کادر گفتگوی اصالت‌سنجی زیست‌سنجشی نشان می‌دهد، می‌توانید به سیستم اشاره کنید که کاربر نیازی به تأیید اصالت‌سنجی ندارد. این راهنمایی می‌تواند به کاربر اجازه دهد پس‌از اصالت‌سنجی مجدد بااستفاده از روشی غیرفعال، مانند تشخیص چهره یا عنبیه، محتوا را سریع‌تر در برنامه‌تان مشاهده کند. برای ارائه این راهنمایی، false را به روش setConfirmationRequired() منتقل کنید.

شکل ۲ دو نسخه از یک کادر گفتگو را نشان می‌دهد. یک نسخه به کنش صریح کاربر نیاز دارد و نسخه دیگر به این کنش نیاز ندارد.

ضبط صفحه‌نمایش چارگوش گفتگو ضبط صفحه‌نمایش چارگوش گفتگو
شکل ۲. اصالت‌سنجی با چهره بدون تأیید کاربر (بالا) و با تأیید کاربر (پایین).

تکه‌کد زیر نشان می‌دهد که چگونه می‌توان کادر گفتگویی را ارائه کرد که برای تکمیل فرایند اصالت‌سنجی به کنش صریح کاربر نیاز ندارد:

کاتلین

// Lets the user authenticate without performing an action, such as pressing a
// button, after their biometric credential is accepted.
promptInfo = BiometricPrompt.PromptInfo.Builder()
        .setTitle("Biometric login for my app")
        .setSubtitle("Log in using your biometric credential")
        .setNegativeButtonText("Use account password")
        .setConfirmationRequired(false)
        .build()

جاوا

// Lets the user authenticate without performing an action, such as pressing a
// button, after their biometric credential is accepted.
promptInfo = new BiometricPrompt.PromptInfo.Builder()
        .setTitle("Biometric login for my app")
        .setSubtitle("Log in using your biometric credential")
        .setNegativeButtonText("Use account password")
        .setConfirmationRequired(false)
        .build();

اجازه دادن به بازگشت به اعتبارنامه‌های غیرزیست‌سنجشی

اگر می‌خواهید برنامه‌تان اجازه دهد اصالت‌سنجی بااستفاده از اعتبارنامه زیست‌سنجشی یا دستگاه انجام شود، می‌توانید با گنجاندن DEVICE_CREDENTIAL در مجموعه مقادیری که به setAllowedAuthenticators() ارسال می‌کنید، اعلام کنید که برنامه‌تان از اعتبارنامه دستگاه پشتیبانی می‌کند.

اگر برنامه‌تان درحال‌حاضر از createConfirmDeviceCredentialIntent() یا setDeviceCredentialAllowed() برای ارائه این قابلیت استفاده می‌کند، به استفاده از setAllowedAuthenticators() بروید. createConfirmDeviceCredentialIntent() در سطح میانای برنامه‌سازی کاربردی ۲۹ منسوخ شده است، و setDeviceCredentialAllowed() در Biometric 1.1.0 منسوخ شده است.

منابع بیشتر

برای کسب اطلاعات بیشتر درباره اصالت‌سنجی زیست‌سنجشی در Android، به منابع زیر مراجعه کنید.

پست‌های وبلاگ