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

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

به‌عنوان یک قانون کلی، باید از Credential Manager برای ورود به سیستم اولیه در دستگاه استفاده کنید. صدور مجدد مجوزهای بعدی را می‌توان با «پیام‌واره زیست‌سنجشی» یا 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 10 و نسخه‌های پایین‌تر، از روش KeyguardManager.isDeviceSecure() استفاده کنید.

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

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

کاتلین

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() بروید.

منابع بیشتر

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

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