让用户通过 Twitter 账号登录

本文档介绍如何使用 Identity Platform 让用户通过 Twitter 登录。

准备工作

本教程假定您已启用 Identity Platform,并且拥有一个使用 HTML 和 JavaScript 编写的基本 Web 应用。如需了解具体方法,请参阅快速入门

将 Twitter 配置为提供商

如需将 Twitter 配置为身份提供商,请执行以下操作:

  1. 前往 Google Cloud 控制台中的身份提供方页面。

    转到“身份提供商”页面

  2. 点击添加提供商

  3. 从列表中选择 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 Client SDK。

  8. 点击保存

让用户通过 Client SDK 登录

  1. 创建 Twitter 提供商对象实例:

    Web 版本 9

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

    Web 版本 8

    var provider = new firebase.auth.TwitterAuthProvider();
  1. 可选:对身份验证流程进行本地化。您可以指定语言,也可以使用设备的默认语言:

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

    Web 版本 8

    firebase.auth().languageCode = 'it';
    // To apply the default browser preference instead of explicitly setting it.
    // firebase.auth().useDeviceLanguage();
  2. 可选:指定其他自定义 OAuth 参数。这些参数是针对 Twitter 的,通常用于自定义身份验证体验。您无法传递 OAuth 或 Identity Platform 预留的参数。

Web 版本 9

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

Web 版本 8

provider.setCustomParameters({
  'lang': 'es'
});
  1. 使用 Twitter 提供商对象让用户登录。您可以打开一个弹出式窗口,也可以重定向当前网页。对于移动设备用户而言,重定向更为便捷。

    如需显示弹出式窗口,请调用 signInWithPopup()

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

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

    如需重定向页面,请先调用 signInWithRedirect()

    使用 signInWithRedirectlinkWithRedirectreauthenticateWithRedirect 时,请遵循最佳实践

    Web 版本 9

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

    Web 版本 8

    firebase.auth().signInWithRedirect(provider);

    然后,在网页加载时调用 getRedirectResult() 来检索 Twitter 令牌:

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

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

获得访问令牌后,您就可以使用它来调用 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"'

手动让用户登录

如果您不想使用 Client SDK,也可以手动处理登录流程:

  1. 按照开发者文档中的步骤将 Twitter 身份验证机制集成到您的应用中。

  2. 使用您在上一步中实现的流程让用户通过 Twitter 登录。

  3. 用您从 Twitter 收到的令牌交换 Identity Platform 凭据:

    Web 版本 9

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

    Web 版本 8

    var credential = firebase.auth.TwitterAuthProvider.credential(accessToken, secret);
  4. 使用该凭据让用户通过 Identity Platform 登录:

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

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

后续步骤