让用户通过 Google 账号登录

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

准备工作

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

将 Google 配置为提供商

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

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

    转到“身份提供商”页面

  2. 点击添加提供商

  3. 从列表中选择 Google

  4. 输入您的 Google Web 客户端 IDWeb 密钥。如果您还没有 ID 和密钥,则可以从 API 和服务页面获取一个。

  5. 配置 Google 下列出的 URI 配置为 Google 应用的有效 OAuth 重定向 URI。如果您在 Identity Platform 中配置了自定义网域,请更新 Google 应用配置中的重定向 URI 以使用自定义网域而不是默认网域。例如,将 https://myproject.firebaseapp.com/__/auth/handler 更改为 https://auth.myownpersonaldomain.com/__/auth/handler

  6. 点击已获授权的网域下的添加网域,以注册您应用的网域。出于开发目的,localhost 默认处于启用状态。

  7. 配置您的应用下,点击设置详情。将代码段复制到应用的代码中,以初始化 Identity Platform Client SDK。

  8. 点击保存

让用户通过 Client SDK 登录

  1. 创建 Google 提供方对象实例:

    Web 版本 9

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

    Web 版本 8

    var provider = new firebase.auth.GoogleAuthProvider();
  1. 可选:添加 OAuth 范围。范围指定您要从 Google 请求哪些数据。更敏感的数据可能需要特定范围。如需确定您的应用所需的范围,请参阅提供商的文档

    Web 版本 9

    provider.addScope('https://www.googleapis.com/auth/contacts.readonly');

    Web 版本 8

    provider.addScope('https://www.googleapis.com/auth/contacts.readonly');
  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 参数。这些参数是针对 Google 的,通常用于自定义身份验证体验。您无法传递 OAuth 或 Identity Platform 预留的参数。

Web 版本 9

provider.setCustomParameters({
  'login_hint': 'user@example.com'
});

Web 版本 8

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

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

    Web 版本 9

    import { getAuth, signInWithPopup, GoogleAuthProvider } from "firebase/auth";
    
    const auth = getAuth();
    signInWithPopup(auth, provider)
      .then((result) => {
        // This gives you a Google Access Token. You can use it to access the Google API.
        const credential = GoogleAuthProvider.credentialFromResult(result);
        const token = credential.accessToken;
        // 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 = GoogleAuthProvider.credentialFromError(error);
        // ...
      });

    Web 版本 8

    firebase.auth()
      .signInWithPopup(provider)
      .then((result) => {
        /** @type {firebase.auth.OAuthCredential} */
        var credential = result.credential;
    
        // This gives you a Google Access Token. You can use it to access the Google API.
        var token = credential.accessToken;
        // 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() 来检索 Google 令牌:

    Web 版本 9

    import { getAuth, getRedirectResult, GoogleAuthProvider } from "firebase/auth";
    
    const auth = getAuth();
    getRedirectResult(auth)
      .then((result) => {
        // This gives you a Google Access Token. You can use it to access Google APIs.
        const credential = GoogleAuthProvider.credentialFromResult(result);
        const token = credential.accessToken;
    
        // 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 = GoogleAuthProvider.credentialFromError(error);
        // ...
      });

    Web 版本 8

    firebase.auth()
      .getRedirectResult()
      .then((result) => {
        if (result.credential) {
          /** @type {firebase.auth.OAuthCredential} */
          var credential = result.credential;
    
          // This gives you a Google Access Token. You can use it to access the Google API.
          var token = credential.accessToken;
          // ...
        }
        // 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;
        // ...
      });

获得访问令牌后,您就可以使用它来调用 Google API。例如:

REST

curl -H "Authorization: Bearer [TOKEN]" https://www.googleapis.com/oauth2/v2/userinfo

手动让用户登录

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

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

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

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

    Web 版本 9

    import { GoogleAuthProvider } from "firebase/auth";
    
    const credential = GoogleAuthProvider.credential(idToken);

    Web 版本 8

    var credential = firebase.auth.GoogleAuthProvider.credential(idToken);
  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;
        // ...
      });

后续步骤