您可以让您的用户使用他们的 Google 帐户通过 Firebase 进行身份验证。您可以使用 Firebase SDK 执行 Google 登录流程,或者使用 Sign In With Google 库手动执行登录流程并将生成的 ID 令牌传递给 Firebase。
在你开始之前
- 将 Firebase 添加到您的 JavaScript 项目。
- 在 Firebase 控制台中启用 Google 作为登录方法:
- 在Firebase 控制台中,打开Auth部分。
- 在登录方法选项卡上,启用Google登录方法并单击保存。
使用 Firebase SDK 处理登录流程
如果您正在构建 Web 应用程序,使用用户的 Google 帐户通过 Firebase 对用户进行身份验证的最简单方法是使用 Firebase JavaScript SDK 处理登录流程。 (如果您想在 Node.js 或其他非浏览器环境中对用户进行身份验证,则必须手动处理登录流程。)
要使用 Firebase JavaScript SDK 处理登录流程,请执行以下步骤:
- 创建 Google 提供程序对象的实例:
Web version 9
import { GoogleAuthProvider } from "firebase/auth"; const provider = new GoogleAuthProvider();
Web version 8
var provider = new firebase.auth.GoogleAuthProvider();
- 可选:指定您要从身份验证提供程序请求的其他 OAuth 2.0 范围。要添加范围,请调用
addScope
。例如:请参阅身份验证提供程序文档。Web version 9
provider.addScope('https://www.googleapis.com/auth/contacts.readonly');
Web version 8
provider.addScope('https://www.googleapis.com/auth/contacts.readonly');
- 可选:要将提供商的 OAuth 流程本地化为用户的首选语言而不显式传递相关的自定义 OAuth 参数,请在启动 OAuth 流程之前更新 Auth 实例上的语言代码。例如:
Web version 9
import { getAuth } from "firebase/auth"; const auth = getAuth(); auth.languageCode = 'it'; // To apply the default browser preference instead of explicitly setting it. // firebase.auth().useDeviceLanguage();
Web version 8
firebase.auth().languageCode = 'it'; // To apply the default browser preference instead of explicitly setting it. // firebase.auth().useDeviceLanguage();
- 可选:指定要与 OAuth 请求一起发送的其他自定义 OAuth 提供程序参数。要添加自定义参数,请使用包含 OAuth 提供程序文档指定的密钥和相应值的对象对已初始化的提供程序调用
setCustomParameters
。例如:保留的必需 OAuth 参数是不允许的,将被忽略。有关更多详细信息,请参阅身份验证提供程序参考。Web version 9
provider.setCustomParameters({ 'login_hint': 'user@example.com' });
Web version 8
provider.setCustomParameters({ 'login_hint': 'user@example.com' });
- 使用 Google 提供商对象通过 Firebase 进行身份验证。您可以通过打开弹出窗口或重定向到登录页面来提示您的用户使用他们的 Google 帐户登录。在移动设备上首选重定向方法。
- 要使用弹出窗口登录,请调用
signInWithPopup
:另请注意,您可以检索 Google 提供商的 OAuth 令牌,该令牌可用于使用 Google API 获取其他数据。Web version 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; // ... }).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 version 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; // ... }).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; // ... });
这也是您可以捕获和处理错误的地方。有关错误代码的列表,请查看Auth Reference Docs 。
- 要通过重定向到登录页面登录,请调用
signInWithRedirect
:使用 signInWithRedirect 时遵循最佳实践。然后,您还可以通过在页面加载时调用Web version 9
import { getAuth, signInWithRedirect } from "firebase/auth"; const auth = getAuth(); signInWithRedirect(auth, provider);
Web version 8
firebase.auth().signInWithRedirect(provider);
getRedirectResult
来检索 Google 提供商的 OAuth 令牌:这也是您可以捕获和处理错误的地方。有关错误代码的列表,请查看Auth Reference Docs 。Web version 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; }).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 version 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; }).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 扩展应用,则必须添加您的 Chrome 扩展 ID:
- 在Firebase 控制台中打开您的项目。
- 在身份验证部分中,打开登录方法页面。
- 将如下所示的 URI 添加到授权域列表中:
chrome-extension://CHROME_EXTENSION_ID
只有弹出操作( signInWithPopup
、 linkWithPopup
和reauthenticateWithPopup
)可用于 Chrome 扩展,因为 Chrome 扩展不能使用 HTTP 重定向。您应该从后台页面脚本而不是浏览器操作弹出窗口调用这些方法,因为身份验证弹出窗口将取消浏览器操作弹出窗口。弹出方法只能在使用Manifest V2的扩展中使用。较新的Manifest V3只允许以 service workers 的形式运行后台脚本,根本无法执行弹窗操作。
在 Chrome 扩展程序的清单文件中,确保将https://apis.google.com
URL 添加到content_security_policy
白名单。
下一步
用户首次登录后,将创建一个新的用户帐户并将其链接到用户登录所用的凭据,即用户名和密码、电话号码或身份验证提供商信息。这个新帐户存储为您的 Firebase 项目的一部分,可用于在项目中的每个应用程序中识别用户,无论用户如何登录。
在您的应用程序中,了解用户身份验证状态的推荐方法是在
Auth
对象上设置观察者。然后,您可以从User
对象获取用户的基本个人资料信息。请参阅管理用户。在您的 Firebase Realtime Database 和 Cloud Storage Security Rules中,您可以从
auth
变量中获取登录用户的唯一用户 ID,并使用它来控制用户可以访问的数据。
您可以允许用户使用多个身份验证提供程序登录您的应用程序,方法是将身份验证提供程序凭据链接到现有用户帐户。
要注销用户,请调用signOut
:
Web version 9
import { getAuth, signOut } from "firebase/auth"; const auth = getAuth(); signOut(auth).then(() => { // Sign-out successful. }).catch((error) => { // An error happened. });
Web version 8
firebase.auth().signOut().then(() => { // Sign-out successful. }).catch((error) => { // An error happened. });