Signing in users with Twitter

This document shows you how to use Identity Platform to sign in users with Twitter.

Before you begin

This tutorial assumes you've already enabled Identity Platform, and have a basic web app written using HTML and JavaScript. See the Quickstart to learn how.

Configuring Twitter as a provider

To configure Twitter as an identity provider:

  1. Go to the Identity Providers page in the Google Cloud console.

    Go to the Identity Providers page

  2. Click Add A Provider.

  3. Select Twitter from the list.

  4. Enter your Twitter App ID and App Secret. If you don't already have an ID and secret, you can obtain one from the Twitter Apps page.

  5. Configure the URI listed under Configure Twitter as a valid OAuth redirect URI for your Twitter app. If you configured a custom domain in Identity Platform, update the redirect URI in your Twitter app configuration to use the custom domain instead of the default domain. For example, change https://myproject.firebaseapp.com/__/auth/handler to https://auth.myownpersonaldomain.com/__/auth/handler.

  6. Register your app's domains by clicking Add Domain under Authorized Domains. For development purposes, localhost is already enabled by default.

  7. Under Configure your application, click Setup Details. Copy the snippet into your app's code to initialize the Identity Platform Client SDK.

  8. Click Save.

Signing in users with the Client SDK

  1. Create an instance of the Twitter provider object:

    Web version 9

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

    Web version 8

    var provider = new firebase.auth.TwitterAuthProvider();
  1. Optional: Localize the authentication flow. You can specify a language, or use the device's default language:

    Web version 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();

    Web version 8

    firebase.auth().languageCode = 'it';
    // To apply the default browser preference instead of explicitly setting it.
    // firebase.auth().useDeviceLanguage();
  2. Optional: Specify additional custom OAuth parameters. These are specific to Twitter, and are typically used to customize the authentication experience. You can't pass parameters reserved by OAuth or Identity Platform.

Web version 9

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

Web version 8

provider.setCustomParameters({
  'lang': 'es'
});
  1. Use the Twitter provider object to sign in the user. You can either open a pop-up window, or redirect the current page. Redirecting is easier for users on mobile devices.

    To show a pop-up, call signInWithPopup():

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

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

    To redirect the page, first call signInWithRedirect().

    Follow the best practices when using signInWithRedirect, linkWithRedirect, or reauthenticateWithRedirect.

    Web version 9

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

    Web version 8

    firebase.auth().signInWithRedirect(provider);

    Then, retrieve the Twitter token by calling getRedirectResult() when your page loads:

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

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

Once you have an access token, you can use it to call the Twitter API. For example:

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"'

Signing in users manually

If you don't want to use the Client SDK, you can also handle the sign-in flow manually:

  1. Integrate Twitter authentication into your app by following the steps in their developer documentation.

  2. Sign in the user with Twitter using the flow you implemented in the previous step.

  3. Exchange the token you receive from Twitter for an Identity Platform credential:

    Web version 9

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

    Web version 8

    var credential = firebase.auth.TwitterAuthProvider.credential(accessToken, secret);
  4. Use the credential to sign in the user with Identity Platform:

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

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

What's next