Update(20160521):Firebase 刚刚发布了重大更新Firebase 身份验证 https://firebase.google.com/docs/auth/产品,现在允许单个用户链接来自各个支持的提供商的帐户。要了解有关此功能的更多信息,请阅读以下文档:iOS https://firebase.google.com/docs/auth/ios/account-linking, Web https://firebase.google.com/docs/auth/web/account-linking and Android https://firebase.google.com/docs/auth/android/account-linking。由于历史原因,留下下面的答案。
Firebase 核心服务提供了多种身份验证方法:https://www.firebase.com/docs/security/authentication.html https://www.firebase.com/docs/security/authentication.html
Firebase 的核心使用安全 JWT 令牌进行身份验证。任何导致生成 JWT 令牌的操作(例如在您自己的服务器上使用 JWT 库)都将有助于向 Firebase 对您的用户进行身份验证,因此您可以完全控制身份验证过程。
Firebase 提供了一项名为 Firebase Simple Login 的服务,这是生成这些令牌的一种方法(这提供了我们的 Facebook、Twitter 等身份验证)。它适用于常见的身份验证方案,以便您可以在没有服务器的情况下快速启动并运行,但它不是唯一的身份验证方法,也不是一个全面的解决方案。
以下是允许使用 Firebase Simple Login 登录多个提供商的一种方法:
- 为每个用户存储一个规范的用户标识符,以及一个映射
每个特定于提供商的标识符对应一个规范 ID。
- 更新您的安全规则以匹配上的任何凭据
给定用户帐户,而不仅仅是一个。
实际上,安全规则可能如下所示,假设您想要同时启用 Twitter 和 Facebook 身份验证(或允许用户使用其中之一创建帐户,然后添加另一个帐户):
{
"users": {
"$userid": {
// Require the user to be logged in, and make sure their current credentials
// match at least one of the credentials listed below, unless we're creating
// a new account from scratch.
".write": "auth != null &&
(data.val() === null ||
(auth.provider === 'facebook' && auth.id === data.child('facebook/id').val() ||
(auth.provider === 'twitter' && auth.id === data.child('twitter/id').val()))"
}
},
"user-mappings": {
// Only allow users to read the user id mapping for their own account.
"facebook": {
"$fbuid": {
".read": "auth != null && auth.provider === 'facebook' && auth.id === $fbuid",
".write": "auth != null &&
(data.val() == null ||
root.child('users').child(data.val()).child('facebook-id').val() == auth.id)"
}
},
"twitter": {
"$twuid": {
".read": "auth != null && auth.provider === 'twitter' && auth.id === $twuid",
".write": "auth != null &&
(data.val() == null ||
root.child('users').child(data.val()).child('twitter-id').val() == auth.id)"
}
}
}
}
在此示例中,您存储一个全局用户 ID(可以是您选择的任何内容)并维护 Facebook、Twitter 等身份验证机制与主要用户记录之间的映射。每个用户登录后,您将从用户映射中获取主要用户记录,并使用该 ID 作为用户数据和操作的主要存储。上面还限制和验证了用户映射中的数据,以便只能由在 /users/$userid/(facebook-id|twitter 下已经拥有相同 Facebook、Twitter 等用户 id 的正确用户写入数据-id|etc-id)。
这种方法可以让您快速启动并运行。然而,如果您有复杂的用例并希望完全控制身份验证体验,您可以在自己的服务器上运行自己的身份验证代码。您可以使用许多有用的开源库来执行此操作,例如凡奥特 https://github.com/bnoguchi/everyauth and passport http://passportjs.org.
您还可以使用第三方身份验证提供商进行身份验证。例如,您可以使用Singly https://singly.com/docs/firebase,它具有大量开箱即用的集成,无需您编写任何服务器端代码。