透過 Twitter 登入使用者

本文說明如何使用 Identity Platform 透過 Twitter 登入使用者帳戶。

事前準備

本教學課程假設您已啟用 Identity Platform,並使用 HTML 和 JavaScript 編寫基本網頁應用程式。如要瞭解操作方式,請參閱快速入門導覽課程

將 Twitter 設為提供者

如要將 Twitter 設定為識別資訊提供者,請按照下列步驟操作:

  1. 前往 Google Cloud 控制台的「Identity Providers」(識別資訊提供者) 頁面。

    前往「Identity Providers」頁面

  2. 按一下「Add A Provider」(新增提供者)

  3. 從清單中選取「Twitter」Twitter

  4. 輸入 Twitter 應用程式 ID應用程式密鑰。如果還沒有 ID 和密碼,可以前往 Twitter 應用程式頁面取得。

  5. 將「設定 Twitter」下方列出的 URI 設為 Twitter 應用程式的有效 OAuth 重新導向 URI。如果您在 Identity Platform 中設定了自訂網域,請更新 Twitter 應用程式設定中的重新導向 URI,改用自訂網域,而非預設網域。例如,將 https://myproject.firebaseapp.com/__/auth/handler 變更為 https://auth.myownpersonaldomain.com/__/auth/handler

  6. 按一下「已授權網域」下方的「新增網域」,註冊應用程式的網域。為方便開發,localhost 預設為啟用狀態。

  7. 在「設定應用程式」下方,按一下「設定詳細資料」。將程式碼片段複製到應用程式的程式碼中,初始化 Identity Platform 用戶端 SDK。

  8. 按一下「儲存」

透過用戶端 SDK 登入使用者

  1. 建立 Twitter 供應商物件的執行個體:

    網頁版 9

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

    網頁版 8

    var provider = new firebase.auth.TwitterAuthProvider();
  2. 選用:將驗證流程在地化。你可以指定語言,或使用裝置的預設語言:

    網頁版 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();

    網頁版 8

    firebase.auth().languageCode = 'it';
    // To apply the default browser preference instead of explicitly setting it.
    // firebase.auth().useDeviceLanguage();
  3. 選用:指定其他自訂 OAuth 參數。這些參數是 Twitter 專屬參數,通常用於自訂驗證體驗。您無法傳遞 OAuth 或 Identity Platform 保留的參數。

    網頁版 9

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

    網頁版 8

    provider.setCustomParameters({
      'lang': 'es'
    });
  4. 使用 Twitter 提供者物件登入使用者。您可以開啟彈出式視窗,或重新導向目前頁面。行動裝置使用者更容易重新導向。

    如要顯示彈出式視窗,請呼叫 signInWithPopup()

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

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

    如要重新導向頁面,請先呼叫 signInWithRedirect()

    使用 signInWithRedirectlinkWithRedirectreauthenticateWithRedirect 時,請遵循最佳做法

    網頁版 9

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

    網頁版 8

    firebase.auth().signInWithRedirect(provider);

    然後,在網頁載入時呼叫 getRedirectResult() ,即可擷取 Twitter 權杖:

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

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

取得存取權杖後,即可用來呼叫 Twitter API。例如:

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

手動登入使用者

如果不想使用用戶端 SDK,也可以手動處理登入流程:

  1. 按照 Twitter 開發人員說明文件中的步驟,將 Twitter 驗證功能整合至應用程式。

  2. 使用在上一步實作的流程,透過 Twitter 登入使用者。

  3. 將從 Twitter 收到的權杖換成 Identity Platform 憑證:

    網頁版 9

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

    網頁版 8

    var credential = firebase.auth.TwitterAuthProvider.credential(accessToken, secret);
  4. 使用憑證透過 Identity Platform 登入使用者:

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

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

後續步驟