Collegare più fornitori di autenticazione a un account utilizzando JavaScript

Puoi consentire agli utenti di accedere alla tua app utilizzando più provider di autenticazione collegando le credenziali del provider di autenticazione a un account utente esistente. Gli utenti sono identificabili dallo stesso ID utente Firebase, indipendentemente dal provider di autenticazione utilizzato per accedere. Ad esempio, un utente che ha eseguito l'accesso con una password può collegare un Account Google e accedere con uno dei due metodi in futuro. In alternativa, un utente anonimo può collegare un account Facebook e, in un secondo momento, accedere con Facebook per continuare a utilizzare la tua app.

Prima di iniziare

Aggiungi alla tua app il supporto per due o più provider di autenticazione (possibilmente inclusa l'autenticazione anonima).

Per collegare le credenziali di un provider di autenticazione come Google o Facebook a un account utente esistente:

  1. Esegui l'accesso dell'utente utilizzando un provider o un metodo di autenticazione.
  2. Recupera l'oggetto AuthProvider corrispondente al provider che vuoi collegare all'account dell'utente. Esempi:

    Web

    import { GoogleAuthProvider, FacebookAuthProvider, TwitterAuthProvider, GithubAuthProvider } from "firebase/auth";
    
    const googleProvider = new GoogleAuthProvider();
    const facebookProvider = new FacebookAuthProvider();
    const twitterProvider = new TwitterAuthProvider();
    const githubProvider = new GithubAuthProvider();

    Web

    var googleProvider = new firebase.auth.GoogleAuthProvider();
    var facebookProvider = new firebase.auth.FacebookAuthProvider();
    var twitterProvider = new firebase.auth.TwitterAuthProvider();
    var githubProvider = new firebase.auth.GithubAuthProvider();
  3. Chiedi all'utente di accedere con il provider che vuoi collegare. Puoi chiedere agli utenti di accedere aprendo una finestra popup o reindirizzandoli alla pagina di accesso del provider. Il metodo di reindirizzamento è preferito sui dispositivi mobili.
    • Per accedere con una finestra popup, chiama linkWithPopup:

      Web

      import { getAuth, linkWithPopup, GoogleAuthProvider } from "firebase/auth";
      const provider = new GoogleAuthProvider();
      
      const auth = getAuth();
      linkWithPopup(auth.currentUser, provider).then((result) => {
        // Accounts successfully linked.
        const credential = GoogleAuthProvider.credentialFromResult(result);
        const user = result.user;
        // ...
      }).catch((error) => {
        // Handle Errors here.
        // ...
      });

      Web

      auth.currentUser.linkWithPopup(provider).then((result) => {
        // Accounts successfully linked.
        var credential = result.credential;
        var user = result.user;
        // ...
      }).catch((error) => {
        // Handle Errors here.
        // ...
      });
    • Per accedere reindirizzando alla pagina di accesso del provider, chiama linkWithRedirect: Segui le best practice quando utilizzi "linkWithRedirect".

      Web

      import { getAuth, linkWithRedirect, GoogleAuthProvider } from "firebase/auth";
      const provider = new GoogleAuthProvider();
      
      const auth = getAuth();
      linkWithRedirect(auth.currentUser, provider)
        .then(/* ... */)
        .catch(/* ... */);

      Web

      auth.currentUser.linkWithRedirect(provider)
        .then(/* ... */)
        .catch(/* ... */);
      Dopo aver eseguito l'accesso, l'utente viene reindirizzato alla tua pagina. Poi, puoi recuperare il risultato dell'accesso chiamando getRedirectResult quando la pagina viene caricata:

      Web

      import { getRedirectResult } from "firebase/auth";
      getRedirectResult(auth).then((result) => {
        const credential = GoogleAuthProvider.credentialFromResult(result);
        if (credential) {
          // Accounts successfully linked.
          const user = result.user;
          // ...
        }
      }).catch((error) => {
        // Handle Errors here.
        // ...
      });

      Web

      auth.getRedirectResult().then((result) => {
        if (result.credential) {
          // Accounts successfully linked.
          var credential = result.credential;
          var user = result.user;
          // ...
        }
      }).catch((error) => {
        // Handle Errors here.
        // ...
      });
    Se l'utente ha eseguito l'accesso, il suo account presso il provider viene collegato al suo account nel tuo progetto Firebase.

    Il collegamento degli account non andrà a buon fine se le credenziali sono già collegate a un altro account utente. In questo caso, devi gestire l'unione degli account e dei dati associati in base alle esigenze della tua app:

    Web

    import { getAuth, signInWithCredential, deleteUser } from "firebase/auth";
    
    // The implementation of how you store your user data depends on your application
    const repo = new MyUserDataRepo();
    
    // Get reference to the currently signed-in user
    const auth = getAuth();
    const prevUser = auth.currentUser;
    
    // Get the data which you will want to merge. This should be done now
    // while the app is still signed in as this user.
    const prevUserData = repo.get(prevUser);
    
    try {
      // Sign in user with the account you want to link to
      const result = await signInWithCredential(auth, newCredential);
      console.log("Sign In Success", result);
      const currentUser = result.user;
      const currentUserData = repo.get(currentUser);
    
      // Merge prevUser and currentUser data stored in Firebase.
      // Note: How you handle this is specific to your application
      const mergedData = repo.merge(prevUserData, currentUserData);
    
      // Save the merged data to the new user
      repo.set(currentUser, mergedData);
    
      // Delete the previous user's Firebase Auth account first
      await deleteUser(prevUser);
      repo.delete(prevUser);
    } catch (error) {
      console.log("Sign In Error", error);
    }

    Web

    // The implementation of how you store your user data depends on your application
    var repo = new MyUserDataRepo();
    
    // Get reference to the currently signed-in user
    var prevUser = auth.currentUser;
    
    // Get the data which you will want to merge. This should be done now
    // while the app is still signed in as this user.
    var prevUserData = repo.get(prevUser);
    
    // Sign in user with the account you want to link to
    auth.signInWithCredential(newCredential).then((result) => {
      console.log("Sign In Success", result);
      var currentUser = result.user;
      var currentUserData = repo.get(currentUser);
    
      // Merge prevUser and currentUser data stored in Firebase.
      // Note: How you handle this is specific to your application
      var mergedData = repo.merge(prevUserData, currentUserData);
    
      // Save the merged data to the new user
      repo.set(currentUser, mergedData);
    
      // Delete the previous user's Firebase Auth account first
      return prevUser.delete().then(() => {
        repo.delete(prevUser);
      });
    }).catch((error) => {
      console.log("Sign In Error", error);
    });

Per aggiungere le credenziali di indirizzo email e password a un account utente esistente:

  1. Esegui l'accesso dell'utente utilizzando un provider o un metodo di autenticazione.
  2. Chiedi all'utente di inserire un indirizzo email e una nuova password.
  3. Crea un oggetto AuthCredential con l'indirizzo email e la password:

    Web

    import { EmailAuthProvider } from "firebase/auth";
    
    const credential = EmailAuthProvider.credential(email, password);

    Web

    var credential = firebase.auth.EmailAuthProvider.credential(email, password);
  4. Passa l'oggetto AuthCredential al metodo linkWithCredential dell'utente che ha eseguito l'accesso:

    Web

    import { getAuth, linkWithCredential } from "firebase/auth";
    
    const auth = getAuth();
    linkWithCredential(auth.currentUser, credential)
      .then((usercred) => {
        const user = usercred.user;
        console.log("Account linking success", user);
      }).catch((error) => {
        console.log("Account linking error", error);
      });

    Web

    auth.currentUser.linkWithCredential(credential)
      .then((usercred) => {
        var user = usercred.user;
        console.log("Account linking success", user);
      }).catch((error) => {
        console.log("Account linking error", error);
      });

    La chiamata a linkWithCredential non andrà a buon fine se le credenziali sono già collegate a un altro account utente. In questo caso, devi gestire l'unione degli account e dei dati associati in base alle esigenze della tua app (vedi l'esempio sopra).

A un singolo account utente Firebase possono essere collegati più provider di autenticazione (ad esempio email/password, Google, Facebook), il che consente all'utente di accedere allo stesso account Firebase tramite metodi diversi.

Se scolleghi un provider di autenticazione dall'account di un utente, quest'ultimo non potrà più accedere con quel provider.

Per scollegare un provider di autenticazione da un account utente, passa l'ID provider al metodo unlink. Puoi ottenere gli ID provider dei provider di autenticazione collegati a un utente dalla proprietà providerData.

Web

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

const auth = getAuth();
unlink(auth.currentUser, providerId).then(() => {
  // Auth provider unlinked from account
  // ...
}).catch((error) => {
  // An error happened
  // ...
});

Web

user.unlink(providerId).then(() => {
  // Auth provider unlinked from account
  // ...
}).catch((error) => {
  // An error happened
  // ...
});

Risoluzione dei problemi

Se si verificano errori durante il tentativo di collegare più account, consulta la documentazione sugli indirizzi email verificati.