Aggiungere l'autenticazione a più fattori alla tua app web

Se hai eseguito l'upgrade a Firebase Authentication with Identity Platform, puoi aggiungere l'autenticazione a più fattori tramite SMS alla tua app web.

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

  1. 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.

  2. Attiva le regioni in cui prevedi di utilizzare l'autenticazione SMS. Firebase utilizza una policy per la regione SMS completamente bloccante, che consente di creare i progetti in uno stato più sicuro per impostazione predefinita.

  3. Assicurati che la tua app verifichi le email degli utenti. L'autenticazione a più fattori richiede la verifica email. In questo modo, gli utenti malintenzionati non possono registrarsi a un servizio con un indirizzo email che non è di loro proprietà e bloccare il vero proprietario aggiungendo un secondo fattore.

Utilizzo della multitenancy

Se stai attivando l'autenticazione a più fattori per l'utilizzo in un ambiente multi-tenant, assicurati di completare i seguenti passaggi (oltre al resto delle istruzioni riportate in questo documento):

  1. Nella console Google Cloud, seleziona il tenant con cui vuoi lavorare.

  2. Nel codice, imposta il campo tenantId nell'istanza Auth sull'ID del tuo tenant. Ad esempio:

    Web

    import { getAuth } from "firebase/auth";
    
    const auth = getAuth(app);
    auth.tenantId = "myTenantId1";
    

    Web

    firebase.auth().tenantId = 'myTenantId1';
    

Attivare l'autenticazione a più fattori

  1. Apri la pagina Autenticazione > Metodo di accesso della console Firebase.

  2. 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.

  3. Se non hai ancora autorizzato il dominio della tua app, aggiungilo alla lista consentita nella pagina Autenticazione > Impostazioni della console Firebase.

Scegliere un pattern di registrazione

Puoi scegliere se la tua app richiede l'autenticazione a più fattori e come e quando registrare i tuoi 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 disponibile l'autenticazione a più fattori 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.

Configurazione del programma di verifica reCAPTCHA

Prima di poter inviare codici SMS, devi configurare un programma di verifica reCAPTCHA. Firebase utilizza reCAPTCHA per prevenire abusi assicurandosi che le richieste di verifica del numero di telefono provengano da uno dei domini consentiti della tua app.

Non è necessario configurare manualmente un client reCAPTCHA. L'oggetto RecaptchaVerifier dell'SDK client crea e inizializza automaticamente le chiavi e i secret client necessari.

Utilizzo di reCAPTCHA invisibile

L'oggetto RecaptchaVerifier supporta reCAPTCHA invisibile, che spesso può verificare l'utente senza richiedere alcuna interazione. Per utilizzare un reCAPTCHA invisibile, crea un RecaptchaVerifier con il parametro size impostato su invisible e specifica l'ID dell'elemento UI che avvia la registrazione multifattore:

Web

import { RecaptchaVerifier, getAuth } from "firebase/auth";

const recaptchaVerifier = new RecaptchaVerifier(getAuth(), "sign-in-button", {
    "size": "invisible",
    "callback": function(response) {
        // reCAPTCHA solved, you can proceed with
        // phoneAuthProvider.verifyPhoneNumber(...).
        onSolvedRecaptcha();
    }
});

Web

var recaptchaVerifier = new firebase.auth.RecaptchaVerifier('sign-in-button', {
'size': 'invisible',
'callback': function(response) {
  // reCAPTCHA solved, you can proceed with phoneAuthProvider.verifyPhoneNumber(...).
  onSolvedRecaptcha();
}
});

Utilizzo del widget reCAPTCHA

Per utilizzare un widget reCAPTCHA visibile, crea un elemento HTML per contenere il widget, quindi crea un oggetto RecaptchaVerifier con l'ID del contenitore dell'interfaccia utente. Puoi anche impostare facoltativamente i callback che vengono richiamati quando reCAPTCHA viene risolto o scade:

Web

import { RecaptchaVerifier, getAuth } from "firebase/auth";

const recaptchaVerifier = new RecaptchaVerifier(
    getAuth(),
    "recaptcha-container",

    // Optional reCAPTCHA parameters.
    {
      "size": "normal",
      "callback": function(response) {
        // reCAPTCHA solved, you can proceed with
        // phoneAuthProvider.verifyPhoneNumber(...).
        onSolvedRecaptcha();
      },
      "expired-callback": function() {
        // Response expired. Ask user to solve reCAPTCHA again.
        // ...
      }
    }
);

Web

var recaptchaVerifier = new firebase.auth.RecaptchaVerifier(
  'recaptcha-container',
  // Optional reCAPTCHA parameters.
  {
    'size': 'normal',
    'callback': function(response) {
      // reCAPTCHA solved, you can proceed with phoneAuthProvider.verifyPhoneNumber(...).
      // ...
      onSolvedRecaptcha();
    },
    'expired-callback': function() {
      // Response expired. Ask user to solve reCAPTCHA again.
      // ...
    }
  });

Pre-rendering di reCAPTCHA

Facoltativamente, puoi pre-renderizzare reCAPTCHA prima di iniziare la registrazione a due fattori:

Web

recaptchaVerifier.render()
    .then(function (widgetId) {
        window.recaptchaWidgetId = widgetId;
    });

Web

recaptchaVerifier.render()
  .then(function(widgetId) {
    window.recaptchaWidgetId = widgetId;
  });

Dopo la risoluzione di render(), ricevi l'ID widget di reCAPTCHA, che puoi utilizzare per effettuare chiamate all'API reCAPTCHA:

var recaptchaResponse = grecaptcha.getResponse(window.recaptchaWidgetId);

RecaptchaVerifier astrae questa logica con il metodo verify, quindi non devi gestire direttamente la variabile grecaptcha.

Registrazione di un secondo fattore

Per registrare un nuovo fattore secondario per un utente:

  1. Esegui nuovamente l'autenticazione dell'utente.

  2. Chiedi all'utente di inserire il proprio numero di telefono.

  3. Inizializza il programma di verifica reCAPTCHA come illustrato nella sezione precedente. Salta questo passaggio se un'istanza di RecaptchaVerifier è già configurata:

    Web

    import { RecaptchaVerifier, getAuth } from "firebase/auth";
    
    const recaptchaVerifier = new RecaptchaVerifier(
      getAuth(),'recaptcha-container-id', undefined);
    

    Web

    var recaptchaVerifier = new firebase.auth.RecaptchaVerifier('recaptcha-container-id');
    
  4. Ottieni una sessione con autenticazione a più fattori per l'utente:

    Web

    import { multiFactor } from "firebase/auth";
    
    multiFactor(user).getSession().then(function (multiFactorSession) {
        // ...
    });
    

    Web

    user.multiFactor.getSession().then(function(multiFactorSession) {
      // ...
    })
    
  5. Inizializza un oggetto PhoneInfoOptions con il numero di telefono dell'utente e la sessione di autenticazione a più fattori:

    Web

    // Specify the phone number and pass the MFA session.
    const phoneInfoOptions = {
      phoneNumber: phoneNumber,
      session: multiFactorSession
    };
    

    Web

    // Specify the phone number and pass the MFA session.
    var phoneInfoOptions = {
      phoneNumber: phoneNumber,
      session: multiFactorSession
    };
    
  6. Invia un messaggio di verifica al telefono dell'utente:

    Web

    import { PhoneAuthProvider } from "firebase/auth";
    
    const phoneAuthProvider = new PhoneAuthProvider(auth);
    phoneAuthProvider.verifyPhoneNumber(phoneInfoOptions, recaptchaVerifier)
        .then(function (verificationId) {
            // verificationId will be needed to complete enrollment.
        });
    

    Web

    var phoneAuthProvider = new firebase.auth.PhoneAuthProvider();
    // Send SMS verification code.
    return phoneAuthProvider.verifyPhoneNumber(phoneInfoOptions, recaptchaVerifier)
      .then(function(verificationId) {
        // verificationId will be needed for enrollment completion.
      })
    

    Sebbene non sia obbligatorio, è una best practice informare gli utenti in anticipo che riceveranno un messaggio SMS e che verranno applicate le tariffe standard.

  7. Se la richiesta non va a buon fine, reimposta reCAPTCHA, quindi ripeti il passaggio precedente in modo che l'utente possa riprovare. Tieni presente che verifyPhoneNumber() reimposterà automaticamente reCAPTCHA quando genera un errore, poiché i token reCAPTCHA sono utilizzabili una sola volta.

    Web

    recaptchaVerifier.clear();
    

    Web

    recaptchaVerifier.clear();
    
  8. Una volta inviato il codice SMS, chiedi all'utente di verificarlo:

    Web

    // Ask user for the verification code. Then:
    const cred = PhoneAuthProvider.credential(verificationId, verificationCode);
    

    Web

    // Ask user for the verification code. Then:
    var cred = firebase.auth.PhoneAuthProvider.credential(verificationId, verificationCode);
    
  9. Inizializza un oggetto MultiFactorAssertion con PhoneAuthCredential:

    Web

    import { PhoneMultiFactorGenerator } from "firebase/auth";
    
    const multiFactorAssertion = PhoneMultiFactorGenerator.assertion(cred);
    

    Web

    var multiFactorAssertion = firebase.auth.PhoneMultiFactorGenerator.assertion(cred);
    
  10. Completa la registrazione. Se vuoi, puoi specificare un nome visualizzato per il secondo fattore. Ciò è utile per gli utenti con più fattori secondari, poiché il numero di telefono viene mascherato durante il flusso di autenticazione (ad esempio, +1******1234).

    Web

    // Complete enrollment. This will update the underlying tokens
    // and trigger ID token change listener.
    multiFactor(user).enroll(multiFactorAssertion, "My personal phone number");
    

    Web

    // Complete enrollment. This will update the underlying tokens
    // and trigger ID token change listener.
    user.multiFactor.enroll(multiFactorAssertion, 'My personal phone number');
    

Il codice riportato di seguito mostra un esempio completo di registrazione di un secondo fattore:

Web

import {
    multiFactor, PhoneAuthProvider, PhoneMultiFactorGenerator,
    RecaptchaVerifier, getAuth
} from "firebase/auth";

const recaptchaVerifier = new RecaptchaVerifier(getAuth(),
    'recaptcha-container-id', undefined);
multiFactor(user).getSession()
    .then(function (multiFactorSession) {
        // Specify the phone number and pass the MFA session.
        const phoneInfoOptions = {
            phoneNumber: phoneNumber,
            session: multiFactorSession
        };

        const phoneAuthProvider = new PhoneAuthProvider(auth);

        // Send SMS verification code.
        return phoneAuthProvider.verifyPhoneNumber(phoneInfoOptions, recaptchaVerifier);
    }).then(function (verificationId) {
        // Ask user for the verification code. Then:
        const cred = PhoneAuthProvider.credential(verificationId, verificationCode);
        const multiFactorAssertion = PhoneMultiFactorGenerator.assertion(cred);

        // Complete enrollment.
        return multiFactor(user).enroll(multiFactorAssertion, mfaDisplayName);
    });

Web

var recaptchaVerifier = new firebase.auth.RecaptchaVerifier('recaptcha-container-id');
user.multiFactor.getSession().then(function(multiFactorSession) {
  // Specify the phone number and pass the MFA session.
  var phoneInfoOptions = {
    phoneNumber: phoneNumber,
    session: multiFactorSession
  };
  var phoneAuthProvider = new firebase.auth.PhoneAuthProvider();
  // Send SMS verification code.
  return phoneAuthProvider.verifyPhoneNumber(
      phoneInfoOptions, recaptchaVerifier);
})
.then(function(verificationId) {
  // Ask user for the verification code.
  var cred = firebase.auth.PhoneAuthProvider.credential(verificationId, verificationCode);
  var multiFactorAssertion = firebase.auth.PhoneMultiFactorGenerator.assertion(cred);
  // Complete enrollment.
  return user.multiFactor.enroll(multiFactorAssertion, mfaDisplayName);
});

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:

  1. Accedi all'utente con il primo fattore, quindi rileva l'errore auth/multi-factor-auth-required. Questo errore contiene un resolver, suggerimenti sui secondi fattori registrati e una sessione sottostante che dimostra che l'utente ha eseguito l'autenticazione correttamente con il primo fattore.

    Ad esempio, se il primo fattore dell'utente era un'email e una password:

    Web

    import { getAuth, signInWithEmailAndPassword, getMultiFactorResolver} from "firebase/auth";
    
    const auth = getAuth();
    signInWithEmailAndPassword(auth, email, password)
        .then(function (userCredential) {
            // User successfully signed in and is not enrolled with a second factor.
        })
        .catch(function (error) {
            if (error.code == 'auth/multi-factor-auth-required') {
                // The user is a multi-factor user. Second factor challenge is required.
                resolver = getMultiFactorResolver(auth, error);
                // ...
            } else if (error.code == 'auth/wrong-password') {
                // Handle other errors such as wrong password.
            }
    });
    

    Web

    firebase.auth().signInWithEmailAndPassword(email, password)
      .then(function(userCredential) {
        // User successfully signed in and is not enrolled with a second factor.
      })
      .catch(function(error) {
        if (error.code == 'auth/multi-factor-auth-required') {
          // The user is a multi-factor user. Second factor challenge is required.
          resolver = error.resolver;
          // ...
        } else if (error.code == 'auth/wrong-password') {
          // Handle other errors such as wrong password.
        } ...
      });
    

    Se il primo fattore dell'utente è un provider federato, come OAuth, SAML o OIDC, intercetta l'errore dopo aver chiamato signInWithPopup() o signInWithRedirect().

  2. Se l'utente ha registrato più fattori secondari, chiedigli quale utilizzare:

    Web

    // Ask user which second factor to use.
    // You can get the masked phone number via resolver.hints[selectedIndex].phoneNumber
    // You can get the display name via resolver.hints[selectedIndex].displayName
    
    if (resolver.hints[selectedIndex].factorId ===
        PhoneMultiFactorGenerator.FACTOR_ID) {
        // User selected a phone second factor.
        // ...
    } else if (resolver.hints[selectedIndex].factorId ===
               TotpMultiFactorGenerator.FACTOR_ID) {
        // User selected a TOTP second factor.
        // ...
    } else {
        // Unsupported second factor.
    }
    

    Web

    // Ask user which second factor to use.
    // You can get the masked phone number via resolver.hints[selectedIndex].phoneNumber
    // You can get the display name via resolver.hints[selectedIndex].displayName
    if (resolver.hints[selectedIndex].factorId === firebase.auth.PhoneMultiFactorGenerator.FACTOR_ID) {
      // User selected a phone second factor.
      // ...
    } else if (resolver.hints[selectedIndex].factorId === firebase.auth.TotpMultiFactorGenerator.FACTOR_ID) {
      // User selected a TOTP second factor.
      // ...
    } else {
      // Unsupported second factor.
    }
    
  3. Inizializza il programma di verifica reCAPTCHA come illustrato nella sezione precedente. Salta questo passaggio se un'istanza di RecaptchaVerifier è già configurata:

    Web

    import { RecaptchaVerifier, getAuth } from "firebase/auth";
    
    recaptchaVerifier = new RecaptchaVerifier(getAuth(),
        'recaptcha-container-id', undefined);
    

    Web

    var recaptchaVerifier = new firebase.auth.RecaptchaVerifier('recaptcha-container-id');
    
  4. Inizializza un oggetto PhoneInfoOptions con il numero di telefono dell'utente e la sessione di autenticazione a più fattori. Questi valori sono contenuti nell'oggetto resolver passato all'errore auth/multi-factor-auth-required:

    Web

    const phoneInfoOptions = {
        multiFactorHint: resolver.hints[selectedIndex],
        session: resolver.session
    };
    

    Web

    var phoneInfoOptions = {
      multiFactorHint: resolver.hints[selectedIndex],
      session: resolver.session
    };
    
  5. Invia un messaggio di verifica al telefono dell'utente:

    Web

    // Send SMS verification code.
    const phoneAuthProvider = new PhoneAuthProvider(auth);
    phoneAuthProvider.verifyPhoneNumber(phoneInfoOptions, recaptchaVerifier)
        .then(function (verificationId) {
            // verificationId will be needed for sign-in completion.
        });
    

    Web

    var phoneAuthProvider = new firebase.auth.PhoneAuthProvider();
    // Send SMS verification code.
    return phoneAuthProvider.verifyPhoneNumber(phoneInfoOptions, recaptchaVerifier)
      .then(function(verificationId) {
        // verificationId will be needed for sign-in completion.
      })
    
  6. Se la richiesta non va a buon fine, reimposta reCAPTCHA e ripeti il passaggio precedente in modo che l'utente possa riprovare:

    Web

    recaptchaVerifier.clear();
    

    Web

    recaptchaVerifier.clear();
    
  7. Una volta inviato il codice SMS, chiedi all'utente di verificarlo:

    Web

    const cred = PhoneAuthProvider.credential(verificationId, verificationCode);
    

    Web

    // Ask user for the verification code. Then:
    var cred = firebase.auth.PhoneAuthProvider.credential(verificationId, verificationCode);
    
  8. Inizializza un oggetto MultiFactorAssertion con PhoneAuthCredential:

    Web

    const multiFactorAssertion = PhoneMultiFactorGenerator.assertion(cred);
    

    Web

    var multiFactorAssertion = firebase.auth.PhoneMultiFactorGenerator.assertion(cred);
    
  9. 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 provider:

    Web

    // Complete sign-in. This will also trigger the Auth state listeners.
    resolver.resolveSignIn(multiFactorAssertion)
        .then(function (userCredential) {
            // userCredential will also contain the user, additionalUserInfo, 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,
            // userCredential.additionalUserInfo will contain data related to Google
            // provider that the user signed in with.
            // - user.credential contains the Google OAuth credential.
            // - user.credential.accessToken contains the Google OAuth access token.
            // - user.credential.idToken contains the Google OAuth ID token.
        });
    

    Web

    // Complete sign-in. This will also trigger the Auth state listeners.
    resolver.resolveSignIn(multiFactorAssertion)
      .then(function(userCredential) {
        // userCredential will also contain the user, additionalUserInfo, 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,
        // userCredential.additionalUserInfo will contain data related to Google provider that
        // the user signed in with.
        // user.credential contains the Google OAuth credential.
        // user.credential.accessToken contains the Google OAuth access token.
        // user.credential.idToken contains the Google OAuth ID token.
      });
    

Il codice seguente mostra un esempio completo di accesso di un utente con autenticazione a più fattori:

Web

import {
    getAuth,
    getMultiFactorResolver,
    PhoneAuthProvider,
    PhoneMultiFactorGenerator,
    RecaptchaVerifier,
    signInWithEmailAndPassword
} from "firebase/auth";

const recaptchaVerifier = new RecaptchaVerifier(getAuth(),
    'recaptcha-container-id', undefined);

const auth = getAuth();
signInWithEmailAndPassword(auth, email, password)
    .then(function (userCredential) {
        // User is not enrolled with a second factor and is successfully
        // signed in.
        // ...
    })
    .catch(function (error) {
        if (error.code == 'auth/multi-factor-auth-required') {
            const resolver = getMultiFactorResolver(auth, error);
            // Ask user which second factor to use.
            if (resolver.hints[selectedIndex].factorId ===
                PhoneMultiFactorGenerator.FACTOR_ID) {
                const phoneInfoOptions = {
                    multiFactorHint: resolver.hints[selectedIndex],
                    session: resolver.session
                };
                const phoneAuthProvider = new PhoneAuthProvider(auth);
                // Send SMS verification code
                return phoneAuthProvider.verifyPhoneNumber(phoneInfoOptions, recaptchaVerifier)
                    .then(function (verificationId) {
                        // Ask user for the SMS verification code. Then:
                        const cred = PhoneAuthProvider.credential(
                            verificationId, verificationCode);
                        const multiFactorAssertion =
                            PhoneMultiFactorGenerator.assertion(cred);
                        // Complete sign-in.
                        return resolver.resolveSignIn(multiFactorAssertion)
                    })
                    .then(function (userCredential) {
                        // User successfully signed in with the second factor phone number.
                    });
            } else if (resolver.hints[selectedIndex].factorId ===
                       TotpMultiFactorGenerator.FACTOR_ID) {
                // Handle TOTP MFA.
                // ...
            } else {
                // Unsupported second factor.
            }
        } else if (error.code == 'auth/wrong-password') {
            // Handle other errors such as wrong password.
        }
    });

Web

var resolver;
firebase.auth().signInWithEmailAndPassword(email, password)
  .then(function(userCredential) {
    // User is not enrolled with a second factor and is successfully signed in.
    // ...
  })
  .catch(function(error) {
    if (error.code == 'auth/multi-factor-auth-required') {
      resolver = error.resolver;
      // Ask user which second factor to use.
      if (resolver.hints[selectedIndex].factorId ===
          firebase.auth.PhoneMultiFactorGenerator.FACTOR_ID) {
        var phoneInfoOptions = {
          multiFactorHint: resolver.hints[selectedIndex],
          session: resolver.session
        };
        var phoneAuthProvider = new firebase.auth.PhoneAuthProvider();
        // Send SMS verification code
        return phoneAuthProvider.verifyPhoneNumber(phoneInfoOptions, recaptchaVerifier)
          .then(function(verificationId) {
            // Ask user for the SMS verification code.
            var cred = firebase.auth.PhoneAuthProvider.credential(
                verificationId, verificationCode);
            var multiFactorAssertion =
                firebase.auth.PhoneMultiFactorGenerator.assertion(cred);
            // Complete sign-in.
            return resolver.resolveSignIn(multiFactorAssertion)
          })
          .then(function(userCredential) {
            // User successfully signed in with the second factor phone number.
          });
      } else if (resolver.hints[selectedIndex].factorId ===
        firebase.auth.TotpMultiFactorGenerator.FACTOR_ID) {
        // Handle TOTP MFA.
        // ...
      } else {
        // Unsupported second factor.
      }
    } else if (error.code == 'auth/wrong-password') {
      // Handle other errors such as wrong password.
    } ...
  });

Complimenti! Hai eseguito l'accesso a un utente utilizzando l'autenticazione a più fattori.

Passaggi successivi