让用户通过 Google 登录

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

准备工作

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

将 Google 配置为提供商

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

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

    前往“身份提供商”页面

  2. 点击添加提供商。
  3. 从列表中选择 Google。
  4. 输入您的 Google Web 客户端 ID 和 Web 密钥。 如果您还没有 ID 和密钥,则可以从 API 和服务页面获取一个。
  5. 如要允许使用外部客户端 ID 访问,请点击 添加,然后添加您的客户端 ID。
  6. 如需配置同意屏幕,请点击配置屏幕。系统会在单独的标签页中打开 Google 身份验证平台页面。
  7. 在 Google Auth 平台页面中, 配置 OAuth 权限请求页面。
  8. 返回到身份提供方页面,在项目设置侧边栏中,点击添加网域,然后添加应用的网域。

    我们建议您不要在正式版项目中包含 localhost。

  9. 在配置您的应用部分,点击设置详细信息。将代码段复制到应用的代码中,以初始化 Identity Platform 客户端 SDK。
  10. 点击保存。

让用户通过客户端 SDK 登录

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

    Web 版本 9

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

    Web 版本 8

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

    Web 版本 9

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

    Web 版本 8

    provider.addScope('https://www.googleapis.com/auth/contacts.readonly');
  3. 可选:对身份验证流程进行本地化。您可以指定语言,也可以使用设备的默认语言:

    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();
  4. 可选:指定其他自定义 OAuth 参数。这些参数是针对 Google 的,通常用于自定义身份验证体验。您无法传递 OAuth 或 Identity Platform 预留的参数。

    Web 版本 9

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

    Web 版本 8

    provider.setCustomParameters({
      'login_hint': 'user@example.com'
    });
  5. 使用 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()。

    使用 signInWithRedirect、linkWithRedirect 或 reauthenticateWithRedirect 时,请遵循最佳实践。

    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

手动让用户登录

如果您不想使用客户端 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;
        // ...
      });

后续步骤