Autenticarsi utilizzando Twitter in JavaScript

Puoi consentire ai tuoi utenti di autenticarsi con Firebase utilizzando i loro account Twitter integrando l'autenticazione Twitter nella tua app. Puoi integrare l'autenticazione di Twitter utilizzando l'SDK di Firebase per eseguire il flusso di accesso oppure eseguendo manualmente il flusso OAuth di Twitter e passando il token di accesso e il segreto risultanti a Firebase.

Prima di iniziare

  1. Aggiungi Firebase al tuo progetto JavaScript .
  2. Nella console Firebase , apri la sezione Autenticazione .
  3. Nella scheda Metodo di accesso , abilita il provider Twitter .
  4. Aggiungi la chiave API e il segreto API dalla console per sviluppatori di quel provider alla configurazione del provider:
    1. Registra la tua app come applicazione per sviluppatori su Twitter e ottieni la chiave API OAuth e il segreto API della tua app.
    2. Assicurati che l'URI di reindirizzamento OAuth Firebase (ad esempio my-app-12345.firebaseapp.com/__/auth/handler ) sia impostato come URL di richiamata di autorizzazione nella pagina delle impostazioni dell'app nella configurazione dell'app Twitter .
  5. Fare clic su Salva .

Gestisci il flusso di accesso con l'SDK Firebase

Se stai creando un'app Web, il modo più semplice per autenticare i tuoi utenti con Firebase utilizzando i loro account Twitter è gestire il flusso di accesso con Firebase JavaScript SDK. (Se desideri autenticare un utente in Node.js o in un altro ambiente diverso dal browser, devi gestire manualmente il flusso di accesso.)

Per gestire il flusso di accesso con l'SDK JavaScript di Firebase, procedi nel seguente modo:

  1. Crea un'istanza dell'oggetto provider Twitter:

    Web modular API

    import { TwitterAuthProvider } from "firebase/auth";
    
    const provider = new TwitterAuthProvider();

    Web namespaced API

    var provider = new firebase.auth.TwitterAuthProvider();
  2. Facoltativo : per localizzare il flusso OAuth del provider nella lingua preferita dell'utente senza passare esplicitamente i parametri OAuth personalizzati pertinenti, aggiorna il codice della lingua sull'istanza Auth prima di avviare il flusso OAuth. Per esempio:

    Web modular API

    import { getAuth } from "firebase/auth";
    
    const auth = getAuth();
    auth.languageCode = 'it';
    // To apply the default browser preference instead of explicitly setting it.
    // auth.useDeviceLanguage();

    Web namespaced API

    firebase.auth().languageCode = 'it';
    // To apply the default browser preference instead of explicitly setting it.
    // firebase.auth().useDeviceLanguage();
  3. Facoltativo : specifica parametri aggiuntivi del provider OAuth personalizzati che desideri inviare con la richiesta OAuth. Per aggiungere un parametro personalizzato, chiama setCustomParameters sul provider inizializzato con un oggetto contenente la chiave come specificato dalla documentazione del provider OAuth e il valore corrispondente. Per esempio:

    Web modular API

    provider.setCustomParameters({
      'lang': 'es'
    });

    Web namespaced API

    provider.setCustomParameters({
      'lang': 'es'
    });
    I parametri OAuth obbligatori e riservati non sono consentiti e verranno ignorati. Per ulteriori dettagli, vedere il riferimento al provider di autenticazione .
  4. Autenticarsi con Firebase utilizzando l'oggetto provider Twitter. Puoi chiedere ai tuoi utenti di accedere con i loro account Twitter aprendo una finestra pop-up o reindirizzando alla pagina di accesso. Il metodo di reindirizzamento è preferito sui dispositivi mobili.
    • Per accedere con una finestra pop-up, chiama signInWithPopup :

      Web modular API

      import { getAuth, signInWithPopup, TwitterAuthProvider } from "firebase/auth";
      
      const auth = getAuth();
      signInWithPopup(auth, provider)
        .then((result) => {
          // This gives you a the Twitter OAuth 1.0 Access Token and Secret.
          // You can use these server side with your app's credentials to access the Twitter API.
          const credential = TwitterAuthProvider.credentialFromResult(result);
          const token = credential.accessToken;
          const secret = credential.secret;
      
          // The signed-in user info.
          const user = result.user;
          // IdP data available using getAdditionalUserInfo(result)
          // ...
        }).catch((error) => {
          // Handle Errors here.
          const errorCode = error.code;
          const errorMessage = error.message;
          // The email of the user's account used.
          const email = error.customData.email;
          // The AuthCredential type that was used.
          const credential = TwitterAuthProvider.credentialFromError(error);
          // ...
        });

      Web namespaced API

      firebase
        .auth()
        .signInWithPopup(provider)
        .then((result) => {
          /** @type {firebase.auth.OAuthCredential} */
          var credential = result.credential;
      
          // This gives you a the Twitter OAuth 1.0 Access Token and Secret.
          // You can use these server side with your app's credentials to access the Twitter API.
          var token = credential.accessToken;
          var secret = credential.secret;
      
          // The signed-in user info.
          var user = result.user;
          // IdP data available in result.additionalUserInfo.profile.
            // ...
        }).catch((error) => {
          // Handle Errors here.
          var errorCode = error.code;
          var errorMessage = error.message;
          // The email of the user's account used.
          var email = error.email;
          // The firebase.auth.AuthCredential type that was used.
          var credential = error.credential;
          // ...
        });
      Tieni inoltre presente che puoi recuperare il token OAuth del provider Twitter che può essere utilizzato per recuperare dati aggiuntivi utilizzando le API di Twitter.

      Qui è anche possibile rilevare e gestire gli errori. Per un elenco dei codici di errore, dai un'occhiata ai documenti di riferimento sull'autenticazione .

    • Per accedere reindirizzando alla pagina di accesso, chiama signInWithRedirect : segui le best practice quando utilizzi "signInWithRedirect".

      Web modular API

      import { getAuth, signInWithRedirect } from "firebase/auth";
      
      const auth = getAuth();
      signInWithRedirect(auth, provider);

      Web namespaced API

      firebase.auth().signInWithRedirect(provider);
      Quindi, puoi anche recuperare il token OAuth del provider Twitter chiamando getRedirectResult quando viene caricata la pagina:

      Web modular API

      import { getAuth, getRedirectResult, TwitterAuthProvider } from "firebase/auth";
      
      const auth = getAuth();
      getRedirectResult(auth)
        .then((result) => {
          // This gives you a the Twitter OAuth 1.0 Access Token and Secret.
          // You can use these server side with your app's credentials to access the Twitter API.
          const credential = TwitterAuthProvider.credentialFromResult(result);
          const token = credential.accessToken;
          const secret = credential.secret;
          // ...
      
          // The signed-in user info.
          const user = result.user;
          // IdP data available using getAdditionalUserInfo(result)
          // ...
        }).catch((error) => {
          // Handle Errors here.
          const errorCode = error.code;
          const errorMessage = error.message;
          // The email of the user's account used.
          const email = error.customData.email;
          // The AuthCredential type that was used.
          const credential = TwitterAuthProvider.credentialFromError(error);
          // ...
        });

      Web namespaced API

      firebase.auth()
        .getRedirectResult()
        .then((result) => {
          if (result.credential) {
            /** @type {firebase.auth.OAuthCredential} */
            var credential = result.credential;
      
            // This gives you a the Twitter OAuth 1.0 Access Token and Secret.
            // You can use these server side with your app's credentials to access the Twitter API.
            var token = credential.accessToken;
            var secret = credential.secret;
            // ...
          }
      
          // The signed-in user info.
          var user = result.user;
          // IdP data available in result.additionalUserInfo.profile.
            // ...
        }).catch((error) => {
          // Handle Errors here.
          var errorCode = error.code;
          var errorMessage = error.message;
          // The email of the user's account used.
          var email = error.email;
          // The firebase.auth.AuthCredential type that was used.
          var credential = error.credential;
          // ...
        });
      Qui è anche possibile rilevare e gestire gli errori. Per un elenco dei codici di errore, dai un'occhiata ai documenti di riferimento sull'autenticazione .

Gestire manualmente il flusso di accesso

Puoi anche autenticarti con Firebase utilizzando un account Twitter gestendo il flusso di accesso chiamando gli endpoint OAuth di Twitter:

  1. Integra l'autenticazione Twitter nella tua app seguendo la documentazione dello sviluppatore . Al termine del flusso di accesso a Twitter, riceverai un token di accesso OAuth e un segreto OAuth.
  2. Se devi accedere a un'applicazione Node.js, invia il token di accesso OAuth e il segreto OAuth all'applicazione Node.js.
  3. Dopo che un utente ha effettuato l'accesso con Twitter, scambia il token di accesso OAuth e il segreto OAuth con una credenziale Firebase:
    var credential = firebase.auth.TwitterAuthProvider.credential(token, secret);
    
  4. Autenticarsi con Firebase utilizzando le credenziali Firebase:

    Web modular API

    import { getAuth, signInWithCredential, FacebookAuthProvider } from "firebase/auth";
    
    // Sign in with the credential from the Facebook user.
    const auth = getAuth();
    signInWithCredential(auth, credential)
      .then((result) => {
        // Signed in 
        const credential = FacebookAuthProvider.credentialFromResult(result);
      })
      .catch((error) => {
        // Handle Errors here.
        const errorCode = error.code;
        const errorMessage = error.message;
        // The email of the user's account used.
        const email = error.customData.email;
        // The AuthCredential type that was used.
        const credential = FacebookAuthProvider.credentialFromError(error);
        // ...
      });

    Web namespaced API

    // Sign in with the credential from the Facebook user.
    firebase.auth().signInWithCredential(credential)
      .then((result) => {
        // Signed in       
        var credential = result.credential;
        // ...
      })
      .catch((error) => {
        // Handle Errors here.
        var errorCode = error.code;
        var errorMessage = error.message;
        // The email of the user's account used.
        var email = error.email;
        // The firebase.auth.AuthCredential type that was used.
        var credential = error.credential;
        // ...
      });

Autenticati con Firebase in un'estensione di Chrome

Se stai creando un'app di estensione per Chrome, consulta la guida Offscreen Documents .

Prossimi passi

Dopo che un utente accede per la prima volta, viene creato un nuovo account utente e collegato alle credenziali, ovvero nome utente e password, numero di telefono o informazioni sul provider di autenticazione, con cui l'utente ha effettuato l'accesso. Questo nuovo account viene archiviato come parte del tuo progetto Firebase e può essere utilizzato per identificare un utente in ogni app del tuo progetto, indipendentemente dalla modalità di accesso dell'utente.

  • Nelle tue app, il modo consigliato per conoscere lo stato di autenticazione del tuo utente è impostare un osservatore sull'oggetto Auth . È quindi possibile ottenere le informazioni di base del profilo dell'utente dall'oggetto User . Vedi Gestisci utenti .

  • Nel tuo Firebase Realtime Database e Cloud Storage Security Rules , puoi ottenere l'ID utente univoco dell'utente che ha effettuato l'accesso dalla variabile auth e utilizzarlo per controllare a quali dati può accedere un utente.

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.

Per disconnettere un utente, chiamare signOut :

Web modular API

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

const auth = getAuth();
signOut(auth).then(() => {
  // Sign-out successful.
}).catch((error) => {
  // An error happened.
});

Web namespaced API

firebase.auth().signOut().then(() => {
  // Sign-out successful.
}).catch((error) => {
  // An error happened.
});
,

Puoi consentire ai tuoi utenti di autenticarsi con Firebase utilizzando i loro account Twitter integrando l'autenticazione Twitter nella tua app. Puoi integrare l'autenticazione di Twitter utilizzando l'SDK di Firebase per eseguire il flusso di accesso oppure eseguendo manualmente il flusso OAuth di Twitter e passando il token di accesso e il segreto risultanti a Firebase.

Prima di iniziare

  1. Aggiungi Firebase al tuo progetto JavaScript .
  2. Nella console Firebase , apri la sezione Autenticazione .
  3. Nella scheda Metodo di accesso , abilita il provider Twitter .
  4. Aggiungi la chiave API e il segreto API dalla console per sviluppatori di quel provider alla configurazione del provider:
    1. Registra la tua app come applicazione per sviluppatori su Twitter e ottieni la chiave API OAuth e il segreto API della tua app.
    2. Assicurati che l'URI di reindirizzamento OAuth Firebase (ad esempio my-app-12345.firebaseapp.com/__/auth/handler ) sia impostato come URL di richiamata di autorizzazione nella pagina delle impostazioni dell'app nella configurazione dell'app Twitter .
  5. Fare clic su Salva .

Gestisci il flusso di accesso con l'SDK Firebase

Se stai creando un'app Web, il modo più semplice per autenticare i tuoi utenti con Firebase utilizzando i loro account Twitter è gestire il flusso di accesso con Firebase JavaScript SDK. (Se desideri autenticare un utente in Node.js o in un altro ambiente diverso dal browser, devi gestire manualmente il flusso di accesso.)

Per gestire il flusso di accesso con l'SDK JavaScript di Firebase, procedi nel seguente modo:

  1. Crea un'istanza dell'oggetto provider Twitter:

    Web modular API

    import { TwitterAuthProvider } from "firebase/auth";
    
    const provider = new TwitterAuthProvider();

    Web namespaced API

    var provider = new firebase.auth.TwitterAuthProvider();
  2. Facoltativo : per localizzare il flusso OAuth del provider nella lingua preferita dell'utente senza passare esplicitamente i parametri OAuth personalizzati pertinenti, aggiorna il codice della lingua sull'istanza Auth prima di avviare il flusso OAuth. Per esempio:

    Web modular API

    import { getAuth } from "firebase/auth";
    
    const auth = getAuth();
    auth.languageCode = 'it';
    // To apply the default browser preference instead of explicitly setting it.
    // auth.useDeviceLanguage();

    Web namespaced API

    firebase.auth().languageCode = 'it';
    // To apply the default browser preference instead of explicitly setting it.
    // firebase.auth().useDeviceLanguage();
  3. Facoltativo : specifica parametri aggiuntivi del provider OAuth personalizzati che desideri inviare con la richiesta OAuth. Per aggiungere un parametro personalizzato, chiama setCustomParameters sul provider inizializzato con un oggetto contenente la chiave come specificato dalla documentazione del provider OAuth e il valore corrispondente. Per esempio:

    Web modular API

    provider.setCustomParameters({
      'lang': 'es'
    });

    Web namespaced API

    provider.setCustomParameters({
      'lang': 'es'
    });
    I parametri OAuth obbligatori e riservati non sono consentiti e verranno ignorati. Per ulteriori dettagli, vedere il riferimento al provider di autenticazione .
  4. Autenticarsi con Firebase utilizzando l'oggetto provider Twitter. Puoi chiedere ai tuoi utenti di accedere con i loro account Twitter aprendo una finestra pop-up o reindirizzando alla pagina di accesso. Il metodo di reindirizzamento è preferito sui dispositivi mobili.
    • Per accedere con una finestra pop-up, chiama signInWithPopup :

      Web modular API

      import { getAuth, signInWithPopup, TwitterAuthProvider } from "firebase/auth";
      
      const auth = getAuth();
      signInWithPopup(auth, provider)
        .then((result) => {
          // This gives you a the Twitter OAuth 1.0 Access Token and Secret.
          // You can use these server side with your app's credentials to access the Twitter API.
          const credential = TwitterAuthProvider.credentialFromResult(result);
          const token = credential.accessToken;
          const secret = credential.secret;
      
          // The signed-in user info.
          const user = result.user;
          // IdP data available using getAdditionalUserInfo(result)
          // ...
        }).catch((error) => {
          // Handle Errors here.
          const errorCode = error.code;
          const errorMessage = error.message;
          // The email of the user's account used.
          const email = error.customData.email;
          // The AuthCredential type that was used.
          const credential = TwitterAuthProvider.credentialFromError(error);
          // ...
        });

      Web namespaced API

      firebase
        .auth()
        .signInWithPopup(provider)
        .then((result) => {
          /** @type {firebase.auth.OAuthCredential} */
          var credential = result.credential;
      
          // This gives you a the Twitter OAuth 1.0 Access Token and Secret.
          // You can use these server side with your app's credentials to access the Twitter API.
          var token = credential.accessToken;
          var secret = credential.secret;
      
          // The signed-in user info.
          var user = result.user;
          // IdP data available in result.additionalUserInfo.profile.
            // ...
        }).catch((error) => {
          // Handle Errors here.
          var errorCode = error.code;
          var errorMessage = error.message;
          // The email of the user's account used.
          var email = error.email;
          // The firebase.auth.AuthCredential type that was used.
          var credential = error.credential;
          // ...
        });
      Tieni inoltre presente che puoi recuperare il token OAuth del provider Twitter che può essere utilizzato per recuperare dati aggiuntivi utilizzando le API di Twitter.

      Qui è anche possibile rilevare e gestire gli errori. Per un elenco dei codici di errore, dai un'occhiata ai documenti di riferimento sull'autenticazione .

    • Per accedere reindirizzando alla pagina di accesso, chiama signInWithRedirect : segui le best practice quando utilizzi "signInWithRedirect".

      Web modular API

      import { getAuth, signInWithRedirect } from "firebase/auth";
      
      const auth = getAuth();
      signInWithRedirect(auth, provider);

      Web namespaced API

      firebase.auth().signInWithRedirect(provider);
      Quindi, puoi anche recuperare il token OAuth del provider Twitter chiamando getRedirectResult quando viene caricata la pagina:

      Web modular API

      import { getAuth, getRedirectResult, TwitterAuthProvider } from "firebase/auth";
      
      const auth = getAuth();
      getRedirectResult(auth)
        .then((result) => {
          // This gives you a the Twitter OAuth 1.0 Access Token and Secret.
          // You can use these server side with your app's credentials to access the Twitter API.
          const credential = TwitterAuthProvider.credentialFromResult(result);
          const token = credential.accessToken;
          const secret = credential.secret;
          // ...
      
          // The signed-in user info.
          const user = result.user;
          // IdP data available using getAdditionalUserInfo(result)
          // ...
        }).catch((error) => {
          // Handle Errors here.
          const errorCode = error.code;
          const errorMessage = error.message;
          // The email of the user's account used.
          const email = error.customData.email;
          // The AuthCredential type that was used.
          const credential = TwitterAuthProvider.credentialFromError(error);
          // ...
        });

      Web namespaced API

      firebase.auth()
        .getRedirectResult()
        .then((result) => {
          if (result.credential) {
            /** @type {firebase.auth.OAuthCredential} */
            var credential = result.credential;
      
            // This gives you a the Twitter OAuth 1.0 Access Token and Secret.
            // You can use these server side with your app's credentials to access the Twitter API.
            var token = credential.accessToken;
            var secret = credential.secret;
            // ...
          }
      
          // The signed-in user info.
          var user = result.user;
          // IdP data available in result.additionalUserInfo.profile.
            // ...
        }).catch((error) => {
          // Handle Errors here.
          var errorCode = error.code;
          var errorMessage = error.message;
          // The email of the user's account used.
          var email = error.email;
          // The firebase.auth.AuthCredential type that was used.
          var credential = error.credential;
          // ...
        });
      Qui è anche possibile rilevare e gestire gli errori. Per un elenco dei codici di errore, dai un'occhiata ai documenti di riferimento sull'autenticazione .

Gestire manualmente il flusso di accesso

Puoi anche autenticarti con Firebase utilizzando un account Twitter gestendo il flusso di accesso chiamando gli endpoint OAuth di Twitter:

  1. Integra l'autenticazione Twitter nella tua app seguendo la documentazione dello sviluppatore . Al termine del flusso di accesso a Twitter, riceverai un token di accesso OAuth e un segreto OAuth.
  2. Se devi accedere a un'applicazione Node.js, invia il token di accesso OAuth e il segreto OAuth all'applicazione Node.js.
  3. Dopo che un utente ha effettuato l'accesso con Twitter, scambia il token di accesso OAuth e il segreto OAuth con una credenziale Firebase:
    var credential = firebase.auth.TwitterAuthProvider.credential(token, secret);
    
  4. Autenticarsi con Firebase utilizzando le credenziali Firebase:

    Web modular API

    import { getAuth, signInWithCredential, FacebookAuthProvider } from "firebase/auth";
    
    // Sign in with the credential from the Facebook user.
    const auth = getAuth();
    signInWithCredential(auth, credential)
      .then((result) => {
        // Signed in 
        const credential = FacebookAuthProvider.credentialFromResult(result);
      })
      .catch((error) => {
        // Handle Errors here.
        const errorCode = error.code;
        const errorMessage = error.message;
        // The email of the user's account used.
        const email = error.customData.email;
        // The AuthCredential type that was used.
        const credential = FacebookAuthProvider.credentialFromError(error);
        // ...
      });

    Web namespaced API

    // Sign in with the credential from the Facebook user.
    firebase.auth().signInWithCredential(credential)
      .then((result) => {
        // Signed in       
        var credential = result.credential;
        // ...
      })
      .catch((error) => {
        // Handle Errors here.
        var errorCode = error.code;
        var errorMessage = error.message;
        // The email of the user's account used.
        var email = error.email;
        // The firebase.auth.AuthCredential type that was used.
        var credential = error.credential;
        // ...
      });

Autenticati con Firebase in un'estensione di Chrome

Se stai creando un'app di estensione per Chrome, consulta la guida Offscreen Documents .

Prossimi passi

Dopo che un utente accede per la prima volta, viene creato un nuovo account utente e collegato alle credenziali, ovvero nome utente e password, numero di telefono o informazioni sul provider di autenticazione, con cui l'utente ha effettuato l'accesso. Questo nuovo account viene archiviato come parte del tuo progetto Firebase e può essere utilizzato per identificare un utente in ogni app del tuo progetto, indipendentemente dalla modalità di accesso dell'utente.

  • Nelle tue app, il modo consigliato per conoscere lo stato di autenticazione del tuo utente è impostare un osservatore sull'oggetto Auth . È quindi possibile ottenere le informazioni di base del profilo dell'utente dall'oggetto User . Vedi Gestisci utenti .

  • Nel tuo Firebase Realtime Database e Cloud Storage Security Rules , puoi ottenere l'ID utente univoco dell'utente che ha effettuato l'accesso dalla variabile auth e utilizzarlo per controllare a quali dati può accedere un utente.

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.

Per disconnettere un utente, chiamare signOut :

Web modular API

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

const auth = getAuth();
signOut(auth).then(() => {
  // Sign-out successful.
}).catch((error) => {
  // An error happened.
});

Web namespaced API

firebase.auth().signOut().then(() => {
  // Sign-out successful.
}).catch((error) => {
  // An error happened.
});
,

Puoi consentire ai tuoi utenti di autenticarsi con Firebase utilizzando i loro account Twitter integrando l'autenticazione Twitter nella tua app. Puoi integrare l'autenticazione di Twitter utilizzando l'SDK di Firebase per eseguire il flusso di accesso oppure eseguendo manualmente il flusso OAuth di Twitter e passando il token di accesso e il segreto risultanti a Firebase.

Prima di iniziare

  1. Aggiungi Firebase al tuo progetto JavaScript .
  2. Nella console Firebase , apri la sezione Autenticazione .
  3. Nella scheda Metodo di accesso , abilita il provider Twitter .
  4. Aggiungi la chiave API e il segreto API dalla console per sviluppatori di quel provider alla configurazione del provider:
    1. Registra la tua app come applicazione per sviluppatori su Twitter e ottieni la chiave API OAuth e il segreto API della tua app.
    2. Assicurati che l'URI di reindirizzamento OAuth Firebase (ad esempio my-app-12345.firebaseapp.com/__/auth/handler ) sia impostato come URL di richiamata di autorizzazione nella pagina delle impostazioni dell'app nella configurazione dell'app Twitter .
  5. Fare clic su Salva .

Gestisci il flusso di accesso con l'SDK Firebase

Se stai creando un'app Web, il modo più semplice per autenticare i tuoi utenti con Firebase utilizzando i loro account Twitter è gestire il flusso di accesso con Firebase JavaScript SDK. (Se desideri autenticare un utente in Node.js o in un altro ambiente diverso dal browser, devi gestire manualmente il flusso di accesso.)

Per gestire il flusso di accesso con l'SDK JavaScript di Firebase, procedi nel seguente modo:

  1. Crea un'istanza dell'oggetto provider Twitter:

    Web modular API

    import { TwitterAuthProvider } from "firebase/auth";
    
    const provider = new TwitterAuthProvider();

    Web namespaced API

    var provider = new firebase.auth.TwitterAuthProvider();
  2. Facoltativo : per localizzare il flusso OAuth del provider nella lingua preferita dell'utente senza passare esplicitamente i parametri OAuth personalizzati pertinenti, aggiorna il codice della lingua sull'istanza Auth prima di avviare il flusso OAuth. Per esempio:

    Web modular API

    import { getAuth } from "firebase/auth";
    
    const auth = getAuth();
    auth.languageCode = 'it';
    // To apply the default browser preference instead of explicitly setting it.
    // auth.useDeviceLanguage();

    Web namespaced API

    firebase.auth().languageCode = 'it';
    // To apply the default browser preference instead of explicitly setting it.
    // firebase.auth().useDeviceLanguage();
  3. Facoltativo : specifica parametri aggiuntivi del provider OAuth personalizzati che desideri inviare con la richiesta OAuth. Per aggiungere un parametro personalizzato, chiama setCustomParameters sul provider inizializzato con un oggetto contenente la chiave come specificato dalla documentazione del provider OAuth e il valore corrispondente. Per esempio:

    Web modular API

    provider.setCustomParameters({
      'lang': 'es'
    });

    Web namespaced API

    provider.setCustomParameters({
      'lang': 'es'
    });
    I parametri OAuth obbligatori e riservati non sono consentiti e verranno ignorati. Per ulteriori dettagli, vedere il riferimento al provider di autenticazione .
  4. Autenticarsi con Firebase utilizzando l'oggetto provider Twitter. Puoi chiedere ai tuoi utenti di accedere con i loro account Twitter aprendo una finestra pop-up o reindirizzando alla pagina di accesso. Il metodo di reindirizzamento è preferito sui dispositivi mobili.
    • Per accedere con una finestra pop-up, chiama signInWithPopup :

      Web modular API

      import { getAuth, signInWithPopup, TwitterAuthProvider } from "firebase/auth";
      
      const auth = getAuth();
      signInWithPopup(auth, provider)
        .then((result) => {
          // This gives you a the Twitter OAuth 1.0 Access Token and Secret.
          // You can use these server side with your app's credentials to access the Twitter API.
          const credential = TwitterAuthProvider.credentialFromResult(result);
          const token = credential.accessToken;
          const secret = credential.secret;
      
          // The signed-in user info.
          const user = result.user;
          // IdP data available using getAdditionalUserInfo(result)
          // ...
        }).catch((error) => {
          // Handle Errors here.
          const errorCode = error.code;
          const errorMessage = error.message;
          // The email of the user's account used.
          const email = error.customData.email;
          // The AuthCredential type that was used.
          const credential = TwitterAuthProvider.credentialFromError(error);
          // ...
        });

      Web namespaced API

      firebase
        .auth()
        .signInWithPopup(provider)
        .then((result) => {
          /** @type {firebase.auth.OAuthCredential} */
          var credential = result.credential;
      
          // This gives you a the Twitter OAuth 1.0 Access Token and Secret.
          // You can use these server side with your app's credentials to access the Twitter API.
          var token = credential.accessToken;
          var secret = credential.secret;
      
          // The signed-in user info.
          var user = result.user;
          // IdP data available in result.additionalUserInfo.profile.
            // ...
        }).catch((error) => {
          // Handle Errors here.
          var errorCode = error.code;
          var errorMessage = error.message;
          // The email of the user's account used.
          var email = error.email;
          // The firebase.auth.AuthCredential type that was used.
          var credential = error.credential;
          // ...
        });
      Tieni inoltre presente che puoi recuperare il token OAuth del provider Twitter che può essere utilizzato per recuperare dati aggiuntivi utilizzando le API di Twitter.

      Qui è anche possibile rilevare e gestire gli errori. Per un elenco dei codici di errore, dai un'occhiata ai documenti di riferimento sull'autenticazione .

    • Per accedere reindirizzando alla pagina di accesso, chiama signInWithRedirect : segui le best practice quando utilizzi "signInWithRedirect".

      Web modular API

      import { getAuth, signInWithRedirect } from "firebase/auth";
      
      const auth = getAuth();
      signInWithRedirect(auth, provider);

      Web namespaced API

      firebase.auth().signInWithRedirect(provider);
      Quindi, puoi anche recuperare il token OAuth del provider Twitter chiamando getRedirectResult quando viene caricata la pagina:

      Web modular API

      import { getAuth, getRedirectResult, TwitterAuthProvider } from "firebase/auth";
      
      const auth = getAuth();
      getRedirectResult(auth)
        .then((result) => {
          // This gives you a the Twitter OAuth 1.0 Access Token and Secret.
          // You can use these server side with your app's credentials to access the Twitter API.
          const credential = TwitterAuthProvider.credentialFromResult(result);
          const token = credential.accessToken;
          const secret = credential.secret;
          // ...
      
          // The signed-in user info.
          const user = result.user;
          // IdP data available using getAdditionalUserInfo(result)
          // ...
        }).catch((error) => {
          // Handle Errors here.
          const errorCode = error.code;
          const errorMessage = error.message;
          // The email of the user's account used.
          const email = error.customData.email;
          // The AuthCredential type that was used.
          const credential = TwitterAuthProvider.credentialFromError(error);
          // ...
        });

      Web namespaced API

      firebase.auth()
        .getRedirectResult()
        .then((result) => {
          if (result.credential) {
            /** @type {firebase.auth.OAuthCredential} */
            var credential = result.credential;
      
            // This gives you a the Twitter OAuth 1.0 Access Token and Secret.
            // You can use these server side with your app's credentials to access the Twitter API.
            var token = credential.accessToken;
            var secret = credential.secret;
            // ...
          }
      
          // The signed-in user info.
          var user = result.user;
          // IdP data available in result.additionalUserInfo.profile.
            // ...
        }).catch((error) => {
          // Handle Errors here.
          var errorCode = error.code;
          var errorMessage = error.message;
          // The email of the user's account used.
          var email = error.email;
          // The firebase.auth.AuthCredential type that was used.
          var credential = error.credential;
          // ...
        });
      Qui è anche possibile rilevare e gestire gli errori. Per un elenco dei codici di errore, dai un'occhiata ai documenti di riferimento sull'autenticazione .

Gestire manualmente il flusso di accesso

Puoi anche autenticarti con Firebase utilizzando un account Twitter gestendo il flusso di accesso chiamando gli endpoint OAuth di Twitter:

  1. Integra l'autenticazione Twitter nella tua app seguendo la documentazione dello sviluppatore . Al termine del flusso di accesso a Twitter, riceverai un token di accesso OAuth e un segreto OAuth.
  2. Se devi accedere a un'applicazione Node.js, invia il token di accesso OAuth e il segreto OAuth all'applicazione Node.js.
  3. Dopo che un utente ha effettuato l'accesso con Twitter, scambia il token di accesso OAuth e il segreto OAuth con una credenziale Firebase:
    var credential = firebase.auth.TwitterAuthProvider.credential(token, secret);
    
  4. Autenticarsi con Firebase utilizzando le credenziali Firebase:

    Web modular API

    import { getAuth, signInWithCredential, FacebookAuthProvider } from "firebase/auth";
    
    // Sign in with the credential from the Facebook user.
    const auth = getAuth();
    signInWithCredential(auth, credential)
      .then((result) => {
        // Signed in 
        const credential = FacebookAuthProvider.credentialFromResult(result);
      })
      .catch((error) => {
        // Handle Errors here.
        const errorCode = error.code;
        const errorMessage = error.message;
        // The email of the user's account used.
        const email = error.customData.email;
        // The AuthCredential type that was used.
        const credential = FacebookAuthProvider.credentialFromError(error);
        // ...
      });

    Web namespaced API

    // Sign in with the credential from the Facebook user.
    firebase.auth().signInWithCredential(credential)
      .then((result) => {
        // Signed in       
        var credential = result.credential;
        // ...
      })
      .catch((error) => {
        // Handle Errors here.
        var errorCode = error.code;
        var errorMessage = error.message;
        // The email of the user's account used.
        var email = error.email;
        // The firebase.auth.AuthCredential type that was used.
        var credential = error.credential;
        // ...
      });

Autenticati con Firebase in un'estensione di Chrome

Se stai creando un'app di estensione per Chrome, consulta la guida Offscreen Documents .

Prossimi passi

Dopo che un utente accede per la prima volta, viene creato un nuovo account utente e collegato alle credenziali, ovvero nome utente e password, numero di telefono o informazioni sul provider di autenticazione, con cui l'utente ha effettuato l'accesso. Questo nuovo account viene archiviato come parte del tuo progetto Firebase e può essere utilizzato per identificare un utente in ogni app del tuo progetto, indipendentemente dalla modalità di accesso dell'utente.

  • Nelle tue app, il modo consigliato per conoscere lo stato di autenticazione del tuo utente è impostare un osservatore sull'oggetto Auth . È quindi possibile ottenere le informazioni di base del profilo dell'utente dall'oggetto User . Vedi Gestisci utenti .

  • Nel tuo Firebase Realtime Database e Cloud Storage Security Rules , puoi ottenere l'ID utente univoco dell'utente che ha effettuato l'accesso dalla variabile auth e utilizzarlo per controllare a quali dati può accedere un utente.

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.

Per disconnettere un utente, chiamare signOut :

Web modular API

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

const auth = getAuth();
signOut(auth).then(() => {
  // Sign-out successful.
}).catch((error) => {
  // An error happened.
});

Web namespaced API

firebase.auth().signOut().then(() => {
  // Sign-out successful.
}).catch((error) => {
  // An error happened.
});