Se hai eseguito l'upgrade a Firebase Authentication with Identity Platform, puoi aggiungere l'autenticazione a più fattori tramite SMS alla tua app per Android.
L'autenticazione a più fattori aumenta la sicurezza della tua app. Mentre gli utenti malintenzionati spesso compromettono password e account social, intercettare un messaggio di testo è più difficile.
Prima di iniziare
- Attiva almeno un provider che supporti l'autenticazione a più fattori. Tutti i provider supportano l'autenticazione a più fattori, ad eccezione dell'autenticazione tramite telefono, dell'autenticazione anonima e di Game Center di Apple. 
- Assicurati che la tua app verifichi le email degli utenti. MFA richiede la verifica email. In questo modo, gli utenti malintenzionati non possono registrarsi a un servizio con un indirizzo email che non possiedono e bloccare il vero proprietario aggiungendo un secondo fattore. 
- Registra l'hash SHA-1 della tua app nella console Firebase (le modifiche verranno trasferite automaticamente a Google Cloud Firebase). - Segui i passaggi descritti in Autenticazione del client per ottenere l'hash SHA-1 della tua app. 
- Apri la Console Firebase. 
- Vai a Impostazioni progetto. 
- Nella sezione Le tue app, fai clic sull'icona Android. 
- Segui i passaggi guidati per aggiungere l'hash SHA-1. 
 
Attivare l'autenticazione a più fattori
- Apri la pagina Autenticazione > Metodo di accesso della console Firebase. 
- Nella sezione Avanzate, attiva Autenticazione a più fattori tramite SMS. - Devi anche inserire i numeri di telefono con cui testerai l'app. Sebbene sia facoltativo, ti consigliamo vivamente di registrare i numeri di telefono per i test al fine di evitare limitazioni durante lo sviluppo. 
- Se non hai ancora autorizzato il dominio della tua app, aggiungilo alla lista consentita nella pagina Autenticazione > Impostazioni della console Firebase. 
- (Facoltativo) Nella pagina Autenticazione > Impostazioni, imposta un criterio per le regioni a cui vuoi consentire o negare l'invio di SMS. L'impostazione di una policy regione SMS può contribuire a proteggere le tue app dagli abusi degli SMS. 
Scegliere un pattern di registrazione
Puoi scegliere se la tua app richiede l'autenticazione a più fattori e come e quando registrare gli utenti. Alcuni pattern comuni includono:
- Registra il secondo fattore dell'utente durante la registrazione. Utilizza questo metodo se la tua app richiede l'autenticazione a più fattori per tutti gli utenti. 
- Offri un'opzione ignorabile per registrare un secondo fattore durante la registrazione. Le app che vogliono incoraggiare, ma non richiedere, l'autenticazione a più fattori potrebbero preferire questo approccio. 
- Offrire la possibilità di aggiungere un secondo fattore dalla pagina di gestione dell'account o del profilo dell'utente, anziché dalla schermata di registrazione. In questo modo, l'attrito durante la procedura di registrazione viene ridotto al minimo, pur rendendo l'autenticazione a più fattori disponibile per gli utenti sensibili alla sicurezza. 
- Richiedi l'aggiunta di un secondo fattore in modo incrementale quando l'utente vuole accedere a funzionalità con requisiti di sicurezza più elevati. 
Registrazione di un secondo fattore
Per registrare un nuovo fattore secondario per un utente:
- Esegui nuovamente l'autenticazione dell'utente. 
- Chiedi all'utente di inserire il proprio numero di telefono. 
- Ottieni una sessione con autenticazione a più fattori per l'utente: - Kotlin- user.multiFactor.session.addOnCompleteListener { task -> if (task.isSuccessful) { val multiFactorSession: MultiFactorSession? = task.result } }- Java- user.getMultiFactor().getSession() .addOnCompleteListener( new OnCompleteListener<MultiFactorSession>() { @Override public void onComplete(@NonNull Task<MultiFactorSession> task) { if (task.isSuccessful()) { MultiFactorSession multiFactorSession = task.getResult(); } } });
- Crea un oggetto - OnVerificationStateChangedCallbacksper gestire diversi eventi nel processo di verifica:- Kotlin- val callbacks = object : OnVerificationStateChangedCallbacks() { override fun onVerificationCompleted(credential: PhoneAuthCredential) { // This callback will be invoked in two situations: // 1) Instant verification. In some cases, the phone number can be // instantly verified without needing to send or enter a verification // code. You can disable this feature by calling // PhoneAuthOptions.builder#requireSmsValidation(true) when building // the options to pass to PhoneAuthProvider#verifyPhoneNumber(). // 2) Auto-retrieval. On some devices, Google Play services can // automatically detect the incoming verification SMS and perform // verification without user action. this@MainActivity.credential = credential } override fun onVerificationFailed(e: FirebaseException) { // This callback is invoked in response to invalid requests for // verification, like an incorrect phone number. if (e is FirebaseAuthInvalidCredentialsException) { // Invalid request // ... } else if (e is FirebaseTooManyRequestsException) { // The SMS quota for the project has been exceeded // ... } // Show a message and update the UI // ... } override fun onCodeSent( verificationId: String, forceResendingToken: ForceResendingToken ) { // The SMS verification code has been sent to the provided phone number. // We now need to ask the user to enter the code and then construct a // credential by combining the code with a verification ID. // Save the verification ID and resending token for later use. this@MainActivity.verificationId = verificationId this@MainActivity.forceResendingToken = forceResendingToken // ... } }- Java- OnVerificationStateChangedCallbacks callbacks = new OnVerificationStateChangedCallbacks() { @Override public void onVerificationCompleted(PhoneAuthCredential credential) { // This callback will be invoked in two situations: // 1) Instant verification. In some cases, the phone number can be // instantly verified without needing to send or enter a verification // code. You can disable this feature by calling // PhoneAuthOptions.builder#requireSmsValidation(true) when building // the options to pass to PhoneAuthProvider#verifyPhoneNumber(). // 2) Auto-retrieval. On some devices, Google Play services can // automatically detect the incoming verification SMS and perform // verification without user action. this.credential = credential; } @Override public void onVerificationFailed(FirebaseException e) { // This callback is invoked in response to invalid requests for // verification, like an incorrect phone number. if (e instanceof FirebaseAuthInvalidCredentialsException) { // Invalid request // ... } else if (e instanceof FirebaseTooManyRequestsException) { // The SMS quota for the project has been exceeded // ... } // Show a message and update the UI // ... } @Override public void onCodeSent( String verificationId, PhoneAuthProvider.ForceResendingToken token) { // The SMS verification code has been sent to the provided phone number. // We now need to ask the user to enter the code and then construct a // credential by combining the code with a verification ID. // Save the verification ID and resending token for later use. this.verificationId = verificationId; this.forceResendingToken = token; // ... } };
- Inizializza un oggetto - PhoneInfoOptionscon il numero di telefono dell'utente, la sessione multifattoriale e i tuoi callback:- Kotlin- val phoneAuthOptions = PhoneAuthOptions.newBuilder() .setPhoneNumber(phoneNumber) .setTimeout(30L, TimeUnit.SECONDS) .setMultiFactorSession(MultiFactorSession) .setCallbacks(callbacks) .build()- Java- PhoneAuthOptions phoneAuthOptions = PhoneAuthOptions.newBuilder() .setPhoneNumber(phoneNumber) .setTimeout(30L, TimeUnit.SECONDS) .setMultiFactorSession(multiFactorSession) .setCallbacks(callbacks) .build();- Per impostazione predefinita, la verifica immediata è abilitata. Per disattivarlo, aggiungi una chiamata a - requireSmsValidation(true).
- Invia un messaggio di verifica al telefono dell'utente: - Kotlin- PhoneAuthProvider.verifyPhoneNumber(phoneAuthOptions)- Java- PhoneAuthProvider.verifyPhoneNumber(phoneAuthOptions);- Sebbene non sia obbligatorio, è una best practice informare gli utenti in anticipo che riceveranno un messaggio SMS e che verranno applicate le tariffe standard. 
- Una volta inviato il codice SMS, chiedi all'utente di verificarlo: - Kotlin- // Ask user for the verification code. val credential = PhoneAuthProvider.getCredential(verificationId, verificationCode)- Java- // Ask user for the verification code. PhoneAuthCredential credential = PhoneAuthProvider.getCredential(verificationId, verificationCode);
- Inizializza un oggetto - MultiFactorAssertioncon- PhoneAuthCredential:- Kotlin- val multiFactorAssertion = PhoneMultiFactorGenerator.getAssertion(credential)- Java- MultiFactorAssertion multiFactorAssertion = PhoneMultiFactorGenerator.getAssertion(credential);
- Completa la registrazione. Se vuoi, puoi specificare un nome visualizzato per il secondo fattore. Ciò è utile per gli utenti con più secondi fattori, poiché il numero di telefono viene mascherato durante il flusso di autenticazione (ad esempio, +1******1234). - Kotlin- // Complete enrollment. This will update the underlying tokens // and trigger ID token change listener. FirebaseAuth.getInstance() .currentUser ?.multiFactor ?.enroll(multiFactorAssertion, "My personal phone number") ?.addOnCompleteListener { // ... }- Java- // Complete enrollment. This will update the underlying tokens // and trigger ID token change listener. FirebaseAuth.getInstance() .getCurrentUser() .getMultiFactor() .enroll(multiFactorAssertion, "My personal phone number") .addOnCompleteListener( new OnCompleteListener<Void>() { @Override public void onComplete(@NonNull Task<Void> task) { // ... } });
Il codice riportato di seguito mostra un esempio completo di registrazione di un secondo fattore:
Kotlin
val multiFactorAssertion = PhoneMultiFactorGenerator.getAssertion(credential)
user.multiFactor.session
    .addOnCompleteListener { task ->
        if (task.isSuccessful) {
            val multiFactorSession = task.result
            val phoneAuthOptions = PhoneAuthOptions.newBuilder()
                .setPhoneNumber(phoneNumber)
                .setTimeout(30L, TimeUnit.SECONDS)
                .setMultiFactorSession(multiFactorSession)
                .setCallbacks(callbacks)
                .build()
            // Send SMS verification code.
            PhoneAuthProvider.verifyPhoneNumber(phoneAuthOptions)
        }
    }
// Ask user for the verification code.
val credential = PhoneAuthProvider.getCredential(verificationId, verificationCode)
val multiFactorAssertion = PhoneMultiFactorGenerator.getAssertion(credential)
// Complete enrollment.
FirebaseAuth.getInstance()
    .currentUser
    ?.multiFactor
    ?.enroll(multiFactorAssertion, "My personal phone number")
    ?.addOnCompleteListener {
        // ...
    }
Java
MultiFactorAssertion multiFactorAssertion = PhoneMultiFactorGenerator.getAssertion(credential);
user.getMultiFactor().getSession()
  .addOnCompleteListener(
      new OnCompleteListener<MultiFactorSession>() {
      @Override
      public void onComplete(@NonNull Task<MultiFactorSession> task) {
        if (task.isSuccessful()) {
          MultiFactorSession multiFactorSession = task.getResult();
          PhoneAuthOptions phoneAuthOptions =
            PhoneAuthOptions.newBuilder()
                .setPhoneNumber(phoneNumber)
                .setTimeout(30L, TimeUnit.SECONDS)
                .setMultiFactorSession(multiFactorSession)
                .setCallbacks(callbacks)
                .build();
          // Send SMS verification code.
          PhoneAuthProvider.verifyPhoneNumber(phoneAuthOptions);
        }
      }
      });
// Ask user for the verification code.
PhoneAuthCredential credential =
  PhoneAuthProvider.getCredential(verificationId, verificationCode);
MultiFactorAssertion multiFactorAssertion = PhoneMultiFactorGenerator.getAssertion(credential);
// Complete enrollment.
FirebaseAuth.getInstance()
  .getCurrentUser()
  .getMultiFactor()
  .enroll(multiFactorAssertion, "My personal phone number")
  .addOnCompleteListener(
      new OnCompleteListener<Void>() {
      @Override
      public void onComplete(@NonNull Task<Void> task) {
        // ...
      }
      });
Complimenti! Hai registrato correttamente un secondo fattore di autenticazione per un utente.
Accesso degli utenti con un secondo fattore
Per accedere a un utente con la verifica via SMS a due fattori:
- Accedi all'utente con il primo fattore, quindi rileva l'eccezione - FirebaseAuthMultiFactorException. Questo errore contiene un resolver, che puoi utilizzare per ottenere i secondi fattori registrati dell'utente. Contiene anche una sessione sottostante che dimostra che l'utente ha eseguito l'autenticazione con il primo fattore.- Ad esempio, se il primo fattore dell'utente era un indirizzo email e una password: - Kotlin- FirebaseAuth.getInstance() .signInWithEmailAndPassword(email, password) .addOnCompleteListener( OnCompleteListener { task -> if (task.isSuccessful) { // User is not enrolled with a second factor and is successfully // signed in. // ... return@OnCompleteListener } if (task.exception is FirebaseAuthMultiFactorException) { // The user is a multi-factor user. Second factor challenge is // required. val multiFactorResolver = (task.exception as FirebaseAuthMultiFactorException).resolver // ... } else { // Handle other errors, such as wrong password. } })- Java- FirebaseAuth.getInstance() .signInWithEmailAndPassword(email, password) .addOnCompleteListener( new OnCompleteListener<AuthResult>() { @Override public void onComplete(@NonNull Task<AuthResult> task) { if (task.isSuccessful()) { // User is not enrolled with a second factor and is successfully // signed in. // ... return; } if (task.getException() instanceof FirebaseAuthMultiFactorException) { // The user is a multi-factor user. Second factor challenge is // required. MultiFactorResolver multiFactorResolver = task.getException().getResolver(); // ... } else { // Handle other errors such as wrong password. } } });- Se il primo fattore dell'utente è un provider federato, ad esempio OAuth, intercetta l'errore dopo aver chiamato - startActivityForSignInWithProvider().
- Se l'utente ha registrato più fattori secondari, chiedigli quale utilizzare: - Kotlin- // Ask user which second factor to use. // You can get the list of enrolled second factors using // multiFactorResolver.hints // Check the selected factor: if (multiFactorResolver.hints[selectedIndex].factorId === PhoneMultiFactorGenerator.FACTOR_ID ) { // User selected a phone second factor. val selectedHint = multiFactorResolver.hints[selectedIndex] as PhoneMultiFactorInfo } else if (multiFactorResolver.hints[selectedIndex].factorId === TotpMultiFactorGenerator.FACTOR_ID) { // User selected a TOTP second factor. } else { // Unsupported second factor. }- Java- // Ask user which second factor to use. // You can get the masked phone number using // resolver.getHints().get(selectedIndex).getPhoneNumber() // You can get the display name using // resolver.getHints().get(selectedIndex).getDisplayName() if ( resolver.getHints() .get(selectedIndex) .getFactorId() .equals( PhoneMultiFactorGenerator.FACTOR_ID ) ) { // User selected a phone second factor. MultiFactorInfo selectedHint = multiFactorResolver.getHints().get(selectedIndex); } else if ( resolver .getHints() .get(selectedIndex) .getFactorId() .equals(TotpMultiFactorGenerator.FACTOR_ID ) ) { // User selected a TOTP second factor. } else { // Unsupported second factor. }
- Inizializza un oggetto - PhoneAuthOptionscon il suggerimento e la sessione multifattoriale. Questi valori sono contenuti nel resolver allegato a- FirebaseAuthMultiFactorException.- Kotlin- val phoneAuthOptions = PhoneAuthOptions.newBuilder() .setMultiFactorHint(selectedHint) .setTimeout(30L, TimeUnit.SECONDS) .setMultiFactorSession(multiFactorResolver.session) .setCallbacks(callbacks) // Optionally disable instant verification. // .requireSmsValidation(true) .build()- Java- PhoneAuthOptions phoneAuthOptions = PhoneAuthOptions.newBuilder() .setMultiFactorHint(selectedHint) .setTimeout(30L, TimeUnit.SECONDS) .setMultiFactorSession(multiFactorResolver.getSession()) .setCallbacks(callbacks) // Optionally disable instant verification. // .requireSmsValidation(true) .build();
- Invia un messaggio di verifica al telefono dell'utente: - Kotlin- // Send SMS verification code PhoneAuthProvider.verifyPhoneNumber(phoneAuthOptions)- Java- // Send SMS verification code PhoneAuthProvider.verifyPhoneNumber(phoneAuthOptions);
- Una volta inviato il codice SMS, chiedi all'utente di verificarlo: - Kotlin- // Ask user for the verification code. Then, pass it to getCredential: val credential = PhoneAuthProvider.getCredential(verificationId, verificationCode)- Java- // Ask user for the verification code. Then, pass it to getCredential: PhoneAuthCredential credential = PhoneAuthProvider.getCredential(verificationId, verificationCode);
- Inizializza un oggetto - MultiFactorAssertioncon- PhoneAuthCredential:- Kotlin- val multiFactorAssertion = PhoneMultiFactorGenerator.getAssertion(credential)- Java- MultiFactorAssertion multiFactorAssertion = PhoneMultiFactorGenerator.getAssertion(credential);
- Chiama il numero - resolver.resolveSignIn()per completare l'autenticazione secondaria. Puoi quindi accedere al risultato di accesso originale, che include i dati e le credenziali di autenticazione standard specifici del fornitore:- Kotlin- multiFactorResolver .resolveSignIn(multiFactorAssertion) .addOnCompleteListener { task -> if (task.isSuccessful) { val authResult = task.result // AuthResult will also contain the user, additionalUserInfo, // and an optional credential (null for email/password) // associated with the first factor sign-in. // For example, if the user signed in with Google as a first // factor, authResult.getAdditionalUserInfo() will contain data // related to Google provider that the user signed in with; // authResult.getCredential() will contain the Google OAuth // credential; // authResult.getCredential().getAccessToken() will contain the // Google OAuth access token; // authResult.getCredential().getIdToken() contains the Google // OAuth ID token. } }- Java- multiFactorResolver .resolveSignIn(multiFactorAssertion) .addOnCompleteListener( new OnCompleteListener<AuthResult>() { @Override public void onComplete(@NonNull Task<AuthResult> task) { if (task.isSuccessful()) { AuthResult authResult = task.getResult(); // AuthResult will also contain the user, additionalUserInfo, // and an optional credential (null for email/password) // associated with the first factor sign-in. // For example, if the user signed in with Google as a first // factor, authResult.getAdditionalUserInfo() will contain data // related to Google provider that the user signed in with. // authResult.getCredential() will contain the Google OAuth // credential. // authResult.getCredential().getAccessToken() will contain the // Google OAuth access token. // authResult.getCredential().getIdToken() contains the Google // OAuth ID token. } } });
Il codice riportato di seguito mostra un esempio completo di accesso di un utente con autenticazione a più fattori:
Kotlin
FirebaseAuth.getInstance()
    .signInWithEmailAndPassword(email, password)
    .addOnCompleteListener { task ->
        if (task.isSuccessful) {
            // User is not enrolled with a second factor and is successfully
            // signed in.
            // ...
            return@addOnCompleteListener
        }
        if (task.exception is FirebaseAuthMultiFactorException) {
            val multiFactorResolver =
                (task.exception as FirebaseAuthMultiFactorException).resolver
            // Ask user which second factor to use. Then, get
            // the selected hint:
            val selectedHint =
                multiFactorResolver.hints[selectedIndex] as PhoneMultiFactorInfo
            // Send the SMS verification code.
            PhoneAuthProvider.verifyPhoneNumber(
                PhoneAuthOptions.newBuilder()
                    .setActivity(this)
                    .setMultiFactorSession(multiFactorResolver.session)
                    .setMultiFactorHint(selectedHint)
                    .setCallbacks(generateCallbacks())
                    .setTimeout(30L, TimeUnit.SECONDS)
                    .build()
            )
            // Ask user for the SMS verification code, then use it to get
            // a PhoneAuthCredential:
            val credential =
                PhoneAuthProvider.getCredential(verificationId, verificationCode)
            // Initialize a MultiFactorAssertion object with the
            // PhoneAuthCredential.
            val multiFactorAssertion: MultiFactorAssertion =
                PhoneMultiFactorGenerator.getAssertion(credential)
            // Complete sign-in.
            multiFactorResolver
                .resolveSignIn(multiFactorAssertion)
                .addOnCompleteListener { task ->
                    if (task.isSuccessful) {
                        // User successfully signed in with the
                        // second factor phone number.
                    }
                    // ...
                }
        } else {
            // Handle other errors such as wrong password.
        }
    }
Java
FirebaseAuth.getInstance()
  .signInWithEmailAndPassword(email, password)
  .addOnCompleteListener(
      new OnCompleteListener<AuthResult>() {
      @Override
      public void onComplete(@NonNull Task<AuthResult> task) {
        if (task.isSuccessful()) {
          // User is not enrolled with a second factor and is successfully
          // signed in.
          // ...
          return;
        }
        if (task.getException() instanceof FirebaseAuthMultiFactorException) {
          FirebaseAuthMultiFactorException e =
            (FirebaseAuthMultiFactorException) task.getException();
          MultiFactorResolver multiFactorResolver = e.getResolver();
          // Ask user which second factor to use.
          MultiFactorInfo selectedHint =
            multiFactorResolver.getHints().get(selectedIndex);
          // Send the SMS verification code.
          PhoneAuthProvider.verifyPhoneNumber(
            PhoneAuthOptions.newBuilder()
                .setActivity(this)
                .setMultiFactorSession(multiFactorResolver.getSession())
                .setMultiFactorHint(selectedHint)
                .setCallbacks(generateCallbacks())
                .setTimeout(30L, TimeUnit.SECONDS)
                .build());
          // Ask user for the SMS verification code.
          PhoneAuthCredential credential =
            PhoneAuthProvider.getCredential(verificationId, verificationCode);
          // Initialize a MultiFactorAssertion object with the
          // PhoneAuthCredential.
          MultiFactorAssertion multiFactorAssertion =
            PhoneMultiFactorGenerator.getAssertion(credential);
          // Complete sign-in.
          multiFactorResolver
            .resolveSignIn(multiFactorAssertion)
            .addOnCompleteListener(
                new OnCompleteListener<AuthResult>() {
                  @Override
                  public void onComplete(@NonNull Task<AuthResult> task) {
                  if (task.isSuccessful()) {
                    // User successfully signed in with the
                    // second factor phone number.
                  }
                  // ...
                  }
                });
        } else {
          // Handle other errors such as wrong password.
        }
      }
      });
Complimenti! Hai eseguito l'accesso a un utente utilizzando l'autenticazione a più fattori.
Passaggi successivi
- Gestisci gli utenti con autenticazione a più fattori in modo programmatico con Admin SDK.