Un metodo per proteggere le informazioni sensibili o i contenuti premium nel tuo è richiedere l'autenticazione biometrica, ad esempio usare il riconoscimento facciale o riconoscimento delle impronte digitali. Questa guida spiega come supportare i flussi di accesso biometrico nella tua app.
Come regola generale, devi utilizzare Gestore delle credenziali per l'accesso iniziale su un dispositivo. Le riautorizzazioni successive possono essere eseguite con la richiesta biometrica o con Gestore delle credenziali. Il vantaggio di usare il prompt biometrico è che offre più opzioni di personalizzazione, mentre Gestore delle credenziali offre l'implementazione in entrambi i flussi.
Dichiarare i tipi di autenticazione supportati dalla tua app
Per definire i tipi di autenticazione supportati dalla tua app, usa la
BiometricManager.Authenticators
a riga di comando. Il sistema ti consente di dichiarare i seguenti tipi di
autenticazione:
BIOMETRIC_STRONG
- Autenticazione tramite un metodo biometrico di Class 3, come definito nella Compatibilità con Android definizione .
BIOMETRIC_WEAK
- Autenticazione tramite un metodo biometrico di Class 2, come definito nella Compatibilità con Android definizione .
DEVICE_CREDENTIAL
- Autenticazione tramite una credenziale di blocco schermo: il PIN, la sequenza o la password dell'utente.
Per iniziare a utilizzare un autenticatore, l'utente deve creare un PIN, sequenza o password. Se l'utente non ne ha già uno, il flusso di registrazione biometrica gli chiede di crearne uno.
Per definire i tipi di autenticazione biometrica accettati dalla tua app, passa un tipo di autenticazione o una combinazione di tipi a livello di bit al metodo setAllowedAuthenticators()
. Il seguente snippet di codice mostra come supportare l'autenticazione utilizzando
una credenziale biometrica di classe 3 o un blocco schermo.
// 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();
Le seguenti combinazioni di tipi di autenticazione non sono supportate su
Android 10 (livello API 29) e versioni precedenti: DEVICE_CREDENTIAL
e
BIOMETRIC_STRONG | DEVICE_CREDENTIAL
. Per verificare la presenza di un PIN:
sequenza o password su Android 10 e versioni precedenti, usa
KeyguardManager.isDeviceSecure()
.
Verificare che sia disponibile l'autenticazione biometrica
Dopo aver deciso quali elementi di autenticazione supporta la tua app, controlla se questi elementi sono disponibili. Per farlo, passa il parametro
la stessa combinazione di tipi a livello di bit che hai dichiarato utilizzando
setAllowedAuthenticators()
nel metodo
canAuthenticate()
.
Se necessario, richiama il metodo
Intenzione di ACTION_BIOMETRIC_ENROLL
un'azione. Nell'extra intent, fornisci l'insieme di autenticatori accettati dalla tua app. Questo intent richiede all'utente di registrare le credenziali per un
di autenticazione accettato dalla tua app.
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; }
Determina come l'utente ha eseguito l'autenticazione
Dopo l'autenticazione dell'utente, puoi verificare se l'utente si è autenticato utilizzando una credenziale del dispositivo o una credenziale biometrica chiamando getAuthenticationType()
.
Mostrare la richiesta di accesso
Per visualizzare un prompt di sistema che richiede all'utente di eseguire l'autenticazione mediante le credenziali biometriche, Libreria biometrica. Questo fornita dal sistema è coerente in tutte le app che la utilizzano, creando un un'esperienza utente più affidabile. Un esempio di finestra di dialogo è riportato nella Figura 1.
Per aggiungere l'autenticazione biometrica alla tua app utilizzando la libreria biometrica: completa i seguenti passaggi:
Nel file
build.gradle
del modulo dell'app, aggiungi una dipendenza dallaandroidx.biometric
libreria.Nell'attività o nel frammento che ospita la finestra di dialogo di accesso biometrico, visualizzala utilizzando la logica mostrata nel seguente snippet di codice:
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); }); }
Utilizza una soluzione crittografica che dipende dall'autenticazione
Per proteggere ulteriormente le informazioni sensibili all'interno della tua app, puoi incorporare la crittografia nel flusso di lavoro di autenticazione biometrica utilizzando un'istanza di CryptoObject
.
Il framework supporta i seguenti oggetti crittografici:
Signature
,
Cipher
e
Mac
.
Dopo che l'utente ha eseguito correttamente l'autenticazione usando un prompt biometrico, la tua app può
eseguire un'operazione crittografica. Ad esempio, se esegui l'autenticazione utilizzando una
Cipher
, la tua app potrà quindi eseguire la crittografia e la decriptazione utilizzando un
SecretKey
.
Le seguenti sezioni illustrano alcuni esempi di utilizzo di un oggetto Cipher
e una
SecretKey
per criptare i dati. Ogni esempio utilizza i seguenti
metodo:
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); }
Esegui l'autenticazione utilizzando solo credenziali biometriche
Se la tua app utilizza una chiave segreta che richiede credenziali biometriche per sbloccarla, l'utente deve autenticare le proprie credenziali biometriche ogni volta prima dell'app accede alla chiave.
Per crittografare le informazioni sensibili solo dopo che l'utente ha eseguito l'autenticazione utilizzando credenziali biometriche, completa i seguenti passaggi:
Genera una chiave che utilizzi la seguente configurazione
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());Avvia un flusso di lavoro di autenticazione biometrica che includa un'algoritmo di crittografia:
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)); });
Nei callback di autenticazione biometrici, usa la chiave segreta per criptare le informazioni sensibili:
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)); }
Effettua l'autenticazione utilizzando credenziali biometriche o sulla schermata di blocco
Puoi usare una chiave segreta che consenta l'autenticazione tramite biometria. credenziali o le credenziali della schermata di blocco (PIN, sequenza o password). Quando configurazione della chiave, specifica un periodo di tempo di validità. Durante questo periodo di tempo, l'app può eseguire più operazioni crittografiche senza che l'utente debba per eseguire nuovamente l'autenticazione.
Per criptare le informazioni sensibili dopo che l'utente si è autenticato utilizzando le credenziali biometriche o della schermata di blocco:
Genera una chiave che utilizza quanto segue
KeyGenParameterSpec
configurazione: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());Entro un periodo di tempo pari a
VALIDITY_DURATION_SECONDS
dopo che l'utente autentica, crittografa le informazioni sensibili: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); } }
Autentica mediante chiavi auth-per-use
Puoi fornire il supporto per le chiavi di autenticazione a consumo all'interno della tua istanza di
BiometricPrompt
. Una chiave di questo tipo richiede all'utente di presentare una credenziale biometrica o una credenziale del dispositivo ogni volta che l'app deve accedere ai dati protetti dalla chiave. Le chiavi di autenticazione per l'utilizzo possono essere utili per transazioni di alto valore, ad esempio per effettuare un pagamento di importo elevato o aggiornare le cartelle cliniche di una persona.
Per associare un oggetto BiometricPrompt
a una chiave di autenticazione per utilizzo, aggiungi codice simile al seguente:
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();
Autenticazione senza un'azione esplicita dell'utente
Per impostazione predefinita, il sistema richiede agli utenti di eseguire un'azione specifica, ad esempio premendo un pulsante dopo che le loro credenziali biometriche sono state accettate. Questo è preferibile se nell'app viene visualizzata la finestra di dialogo per confermare un'azione sensibile o ad alto rischio, come un acquisto.
Tuttavia, se la tua app mostra una finestra di dialogo di autenticazione biometrica per un'azione a rischio inferiore, puoi fornire un suggerimento al sistema che l'utente non deve confermare l'autenticazione. Questo suggerimento può consentire all'utente di visualizzare più rapidamente i contenuti della tua app dopo essersi autenticato di nuovo utilizzando una modalità passiva, ad esempio il riconoscimento basato sul volto o sull'iride. Per fornire questo suggerimento, inserisci false
nel
setConfirmationRequired()
.
La figura 2 mostra due versioni della stessa finestra di dialogo. Una versione richiede un'azione esplicita dell'utente, mentre l'altra no.
Il seguente snippet di codice mostra come presentare una finestra di dialogo che non richiede un'azione esplicita dell'utente per completare la procedura di autenticazione:
// 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();
Consentire il fallback alle credenziali non biometriche
Se vuoi che la tua app consenta l'autenticazione tramite biometria o dispositivo
credenziali, puoi dichiarare che la tua app supporta il dispositivo
credenziali includendo
DEVICE_CREDENTIAL
nell'insieme di valori che trasmetti in
setAllowedAuthenticators()
.
Se attualmente la tua app utilizza
createConfirmDeviceCredentialIntent()
oppure setDeviceCredentialAllowed()
per offrire questa funzionalità, passa all'utilizzo di setAllowedAuthenticators()
.
Risorse aggiuntive
Per scoprire di più sull'autenticazione biometrica su Android, consulta le seguenti risorse Google Cloud.