使用 Google 进行身份验证 (JavaScript)

您可以让用户使用他们的 Google 账号进行 Firebase 身份验证。 您可以使用 Firebase SDK 执行 Google 登录流程,也可以利用“使用 Google 账号登录”库并将生成的 ID 令牌传递给 Firebase 来手动执行登录流程。

准备工作

  1. 将 Firebase 添加至您的 JavaScript 项目
  2. Firebase 控制台中启用 Google 登录方法:
    1. Firebase 控制台中,打开 Auth 部分。
    2. 登录方法标签页中,启用 Google 登录方法并点击保存

使用 Firebase SDK 处理登录流程

如果您是在构建 Web 应用,想要通过用户的 Google 账号对其进行 Firebase 身份验证,最简单的方法是使用 Firebase JavaScript SDK 来处理登录流程(如果您希望在 Node.js 或其他非浏览器环境中对用户进行身份验证,则必须手动处理登录流程)。

如需使用 Firebase JavaScript SDK 处理登录流程,请按以下步骤操作:

  1. 创建 Google 提供方对象实例:
    WebWeb
    import { GoogleAuthProvider } from "firebase/auth";
    
    const provider = new GoogleAuthProvider();
    var provider = new firebase.auth.GoogleAuthProvider();
  2. 可选:指定您希望向身份验证提供方申请的额外 OAuth 2.0 范围。如需添加范围,请调用 addScope。例如:
    WebWeb
    provider.addScope('https://www.googleapis.com/auth/contacts.readonly');
    provider.addScope('https://www.googleapis.com/auth/contacts.readonly');
    请参阅身份验证提供方文档
  3. 可选:如需将提供方的 OAuth 流程本地化为用户偏好的语言,而不明确传递相关自定义 OAuth 参数,请在启动 OAuth 流程之前先更新 Auth 实例中的语言代码。例如:
    WebWeb
    import { getAuth } from "firebase/auth";
    
    const auth = getAuth();
    auth.languageCode = 'it';
    // To apply the default browser preference instead of explicitly setting it.
    // auth.useDeviceLanguage();
    firebase.auth().languageCode = 'it';
    // To apply the default browser preference instead of explicitly setting it.
    // firebase.auth().useDeviceLanguage();
  4. 可选:指定您希望通过 OAuth 请求发送的其他自定义 OAuth 提供方参数。如需添加自定义参数,请使用包含 OAuth 提供方文档中指定的键及相应值的对象,对已初始化的提供方调用 setCustomParameters 方法。例如:
    WebWeb
    provider.setCustomParameters({
      'login_hint': 'user@example.com'
    });
    provider.setCustomParameters({
      'login_hint': 'user@example.com'
    });
    禁止使用保留的必需 OAuth 参数,系统将忽略此类参数。如需了解详情,请参阅身份验证提供方参考文档
  5. 使用 Google 提供方对象进行 Firebase 身份验证。您可以打开弹出式窗口或将用户重定向至登录页面,提示用户使用自己的 Google 账号登录。在移动设备上最好使用重定向方法。
    • 如需使用弹出式窗口登录,请调用 signInWithPopup
      WebWeb
      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);
          // ...
        });
      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;
          // ...
        });
      此外请注意,您可以检索 Google 提供方的 OAuth 令牌,使用该令牌可通过 Google API 提取额外数据。

      您还可以在此处捕获并处理错误。如需获取错误代码列表,请参阅身份验证参考文档

    • 需重定向到登录页面进行登录,请调用 signInWithRedirect:使用“signInWithRedirect”时,请遵循最佳实践
      WebWeb
      import { getAuth, signInWithRedirect } from "firebase/auth";
      
      const auth = getAuth();
      signInWithRedirect(auth, provider);
      firebase.auth().signInWithRedirect(provider);
      此外,您还可以在页面加载时,调用 getRedirectResult 来检索 Google 提供方的 OAuth 令牌:
      WebWeb
      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);
          // ...
        });
      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;
          // ...
        });
      您还可以在此处捕获并处理错误。如需获取错误代码列表,请参阅身份验证参考文档

如果您在 Firebase 控制台中启用了每个电子邮件地址一个账号设置,当用户尝试使用一个 Firebase 用户的提供方(例如 Facebook)中已存在的电子邮件地址登录另一个提供方(例如 Google)时,系统会抛出 auth/account-exists-with-different-credential 错误及 AuthCredential 对象(Google ID 令牌)。如需登录所需的提供方,用户必须首先登录现有提供方 (Facebook),然后再关联到之前的 AuthCredential(Google ID 令牌)。

如果您使用 signInWithPopup,可以通过与下例类似的代码来处理 auth/account-exists-with-different-credential 错误:

import {
  getAuth,
  linkWithCredential,
  signInWithPopup,
  GoogleAuthProvider,
} from "firebase/auth";

try {
  // Step 1: User tries to sign in using Google.
  let result = await signInWithPopup(getAuth(), new GoogleAuthProvider());
} catch (error) {
  // Step 2: User's email already exists.
  if (error.code === "auth/account-exists-with-different-credential") {
    // The pending Google credential.
    let pendingCred = error.credential;

    // Step 3: Save the pending credential in temporary storage,

    // Step 4: Let the user know that they already have an account
    // but with a different provider, and let them choose another
    // sign-in method.
  }
}

// ...

try {
  // Step 5: Sign the user in using their chosen method.
  let result = await signInWithPopup(getAuth(), userSelectedProvider);

  // Step 6: Link to the Google credential.
  // TODO: implement `retrievePendingCred` for your app.
  let pendingCred = retrievePendingCred();

  if (pendingCred !== null) {
    // As you have access to the pending credential, you can directly call the
    // link method.
    let user = await linkWithCredential(result.user, pendingCred);
  }

  // Step 7: Continue to app.
} catch (error) {
  // ...
}

重定向模式

在重定向模式下,处理该错误的方法类似,不同的是待处理凭据必须在页面重定向之间缓存(例如,使用会话存储空间缓存)。

您还可以通过“使用 Google 账号登录”库来处理登录流程,从而使用 Google 账号进行 Firebase 身份验证:

  1. 按照集成指南中的说明,将“使用 Google 账号登录”集成到您的应用中。 务必使用为您的 Firebase 项目生成的 Google 客户端 ID 来配置 Google 登录。您可以在项目开发者控制台的“凭据”页面中找到项目的 Google 客户端 ID。
  2. 在登录结果回调函数中,使用 Google 身份验证响应返回的 ID 令牌来换取 Firebase 凭据,并使用该凭据进行 Firebase 身份验证:
    function handleCredentialResponse(response) {
      // Build Firebase credential with the Google ID token.
      const idToken = response.credential;
      const credential = GoogleAuthProvider.credential(idToken);
    
      // Sign in with credential from the Google user.
      signInWithCredential(auth, credential).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;
        // The credential that was used.
        const credential = GoogleAuthProvider.credentialFromError(error);
        // ...
      });
    }

如需在 Node.js 应用中进行 Firebase 身份验证,请按以下步骤操作:

  1. 使用用户的 Google 账号登录,获取用户的 Google ID 令牌。您可以通过多种方式完成此步骤。例如:
    • 如果您的应用具有浏览器前端,请按照手动处理登录流程部分的说明,使用 Google 登录功能。从身份验证响应中获取 Google ID 令牌:
      var id_token = googleUser.getAuthResponse().id_token
      然后将此令牌发送至您的 Node.js 应用。
    • 如果运行应用的设备的输入功能有限(例如电视),您可以使用在电视和其他设备上进行 Google 登录流程。
  2. 取得用户的 Google ID 令牌之后,使用该令牌构建 Credential 对象,然后使用该凭据进行登录:
    WebWeb
    import { getAuth, signInWithCredential, GoogleAuthProvider } from "firebase/auth";
    
    // Build Firebase credential with the Google ID token.
    const credential = GoogleAuthProvider.credential(id_token);
    
    // Sign in with credential from the Google user.
    const auth = getAuth();
    signInWithCredential(auth, credential).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);
      // ...
    });
    // Build Firebase credential with the Google ID token.
    var credential = firebase.auth.GoogleAuthProvider.credential(id_token);
    
    // Sign in with credential from the Google user.
    firebase.auth().signInWithCredential(credential).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;
      // ...
    });

在 Chrome 扩展程序中进行 Firebase 身份验证

如果您正在构建 Chrome 扩展程序应用,请参阅“屏幕外文档”指南

在创建项目时,Firebase 将为您的项目预配一个唯一的子网域:https://my-app-12345.firebaseapp.com

它也将用作 OAuth 登录的重定向机制。该网域需要列入所有受支持的 OAuth 提供方的许可名单。但是,这意味着用户在登录 Google 时可能会先看到该网域(前往:https://my-app-12345.firebaseapp.com),然后才重定向回应用。

如需避免显示子网域,您可以使用 Firebase Hosting 设置自定义网域:

  1. 按照设置您的 Hosting 网域中的第 1 步到第 3 步执行操作。当您验证网域所有权时,Hosting 会为您的自定义网域预配一个 SSL 证书。
  2. Firebase 控制台中,将您的自定义域名添加到已获授权的域名列表:auth.custom.domain.com
  3. 在 Google 开发者控制台或 OAuth 设置页面中,将可通过该自定义网域访问的重定向页面的网址 (https://auth.custom.domain.com/__/auth/handler) 加入许可名单。
  4. 初始化 JavaScript 库时,使用 authDomain 字段指定您的自定义网域:
    var config = {
      apiKey: '...',
      // Changed from 'PROJECT_ID.firebaseapp.com'.
      authDomain: 'auth.custom.domain.com',
      databaseURL: 'https://PROJECT_ID.firebaseio.com',
      projectId: 'PROJECT_ID',
      storageBucket: 'PROJECT_ID.firebasestorage.app',
      messagingSenderId: 'SENDER_ID'
    };
    firebase.initializeApp(config);

后续步骤

在用户首次登录后,系统会创建一个新的用户账号,并将其与该用户登录时使用的凭据(即用户名和密码、电话号码或者身份验证提供方信息)相关联。此新账号存储在您的 Firebase 项目中,无论用户采用何种方式登录,您项目中的每个应用都可以使用此账号来识别用户。

  • 在您的应用中,建议通过在 Auth 对象上设置观测器来了解用户的身份验证状态。然后,您便可从 User 对象获取用户的基本个人资料信息。请参阅管理用户

  • 在您的 Firebase Realtime DatabaseCloud Storage 安全规则中,您可以从 auth 变量获取已登录用户的唯一用户 ID,然后利用此 ID 来控制用户可以访问哪些数据。

您可以通过将身份验证提供方凭据关联至现有用户账号,让用户可以使用多个身份验证提供方登录您的应用。

如需将用户退出登录,请调用 signOut

WebWeb
import { getAuth, signOut } from "firebase/auth";

const auth = getAuth();
signOut(auth).then(() => {
  // Sign-out successful.
}).catch((error) => {
  // An error happened.
});
firebase.auth().signOut().then(() => {
  // Sign-out successful.
}).catch((error) => {
  // An error happened.
});