Accesso degli utenti con Twitter

Questo documento mostra come utilizzare Identity Platform per eseguire l'accesso degli utenti con Twitter

Prima di iniziare

Questo tutorial presuppone che tu abbia già abilitato Identity Platform e app web di base scritta utilizzando HTML e JavaScript. Consulta le Guida rapida per scoprire come.

Configurazione di Twitter come provider

Per configurare Twitter come provider di identità:

  1. Vai alla pagina Provider di identità nella console Google Cloud.

    Vai alla pagina Provider di identità

  2. Fai clic su Add A Provider (Aggiungi un provider).

  3. Seleziona Twitter dall'elenco.

  4. Inserisci il tuo ID app Twitter e il Segreto dell'app. Se Se ancora non disponi di un ID e di un secret, puoi ottenerne uno dal App Twitter .

  5. Configura l'URI elencato in Configura Twitter come un OAuth valido URI di reindirizzamento per l'app Twitter. Se hai configurato un dominio personalizzato in Identity Platform, aggiorna l'URI di reindirizzamento nella configurazione dell'app Twitter per utilizzare il dominio personalizzato del dominio predefinito. Ad esempio, modifica https://myproject.firebaseapp.com/__/auth/handler in https://auth.myownpersonaldomain.com/__/auth/handler.

  6. Registra i domini dell'app facendo clic su Aggiungi dominio in Domini autorizzati. Ai fini dello sviluppo, localhost è già sono abilitate per impostazione predefinita.

  7. In Configura la tua applicazione, fai clic su Dettagli di configurazione. Copia il nel codice dell'app per inizializzare Identity Platform SDK client.

  8. Fai clic su Salva.

Accesso degli utenti con l'SDK client

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

    Versione web 9

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

    Versione web 8

    var provider = new firebase.auth.TwitterAuthProvider();
  1. (Facoltativo) Localizza il flusso di autenticazione. Puoi specificare una lingua, o utilizza la lingua predefinita del dispositivo:

    Versione web 9

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

    Versione web 8

    firebase.auth().languageCode = 'it';
    // To apply the default browser preference instead of explicitly setting it.
    // firebase.auth().useDeviceLanguage();
  2. Facoltativo:specifica parametri OAuth aggiuntivi personalizzati. Si tratta di specifiche di Twitter e sono generalmente usati per personalizzare un'esperienza di autenticazione efficace. Non puoi trasmettere parametri riservati da OAuth o Identity Platform.

Versione web 9

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

Versione web 8

provider.setCustomParameters({
  'lang': 'es'
});
  1. Utilizza l'oggetto provider Twitter per eseguire l'accesso dell'utente. Puoi aprire una finestra popup o reindirizzare la pagina corrente. Il reindirizzamento è più semplice per gli utenti di dispositivi mobili.

    Per mostrare un popup, chiama signInWithPopup():

    Versione web 9

    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);
        // ...
      });

    Versione web 8

    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;
        // ...
      });

    Per reindirizzare la pagina, devi prima chiamare signInWithRedirect().

    Segui le best practice quando utilizzi signInWithRedirect, linkWithRedirect o reauthenticateWithRedirect.

    Versione web 9

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

    Versione web 8

    firebase.auth().signInWithRedirect(provider);

    Quindi, recupera il token Twitter chiamando getRedirectResult() al caricamento della pagina:

    Versione web 9

    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);
        // ...
      });

    Versione web 8

    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;
        // ...
      });

Una volta ottenuto il token di accesso, puoi utilizzarlo per chiamare l'API Twitter. Ad esempio:

REST

curl --request POST
  --url 'https://api.twitter.com/1.1/statuses/update.json?status=Hello%20world'
  --header 'authorization: OAuth oauth_consumer_key="CONSUMER_API_KEY",
  oauth_nonce="OAUTH_NONCE", oauth_signature="OAUTH_SIGNATURE",
  oauth_signature_method="HMAC-SHA1", oauth_timestamp="OAUTH_TIMESTAMP",
  oauth_token="ACCESS_TOKEN", oauth_version="1.0"'

Accesso manuale degli utenti

Se non vuoi utilizzare l'SDK del client, puoi anche gestire l'accesso flusso manuale:

  1. Integra l'autenticazione Twitter nella tua app seguendo questa procedura nella documentazione per gli sviluppatori.

  2. Esegui l'accesso dell'utente su Twitter utilizzando il flusso implementato in passaggio precedente.

  3. Scambia il token che ricevi da Twitter con un Credenziale Identity Platform:

    Versione web 9

    import { TwitterAuthProvider } from "firebase/auth";
    
    const credential = TwitterAuthProvider.credential(accessToken, secret);

    Versione web 8

    var credential = firebase.auth.TwitterAuthProvider.credential(accessToken, secret);
  4. Utilizza le credenziali per accedere all'utente con Identity Platform:

    Versione web 9

    import { getAuth, signInWithCredential } from "firebase/auth";
    
    // Sign in with the credential from the user.
    const auth = getAuth();
    signInWithCredential(auth, credential)
      .then((result) => {
        // Signed in 
        // ...
      })
      .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;
        // ...
      });

    Versione web 8

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

Passaggi successivi