firebase - 将数据保存到 Firebase 用户对象中

标签 firebase firebase-authentication

使用这个:

firebase.auth().onAuthStateChanged(function(user){
    if (user){

Firebase 正在返回用户,其中包括 userID。 当网页获取此对象时,它会获取用户 ID,并且需要再次访问数据库记录来检查一些非常基本的内容(如果是付费用户,或另一个简单的 key ),以便选择 UI。

是否可以在此回调中返回用户,包括有关他的一些预定义的基本信息?

最佳答案

如果您想向用户帐户添加一些额外信息,则不能使用 User对象,它具有固定的属性列表。

有两种经典方法:

1。创建特定的用户记录

您为每个用户创建一个 Firestore 文档(或实时数据库节点)。通常您使用用户的 uid 作为 Firestore 文档/RTDB 节点的 id。

这意味着您需要获取数据库才能获取这些额外的用户信息,例如

firebase.auth().onAuthStateChanged(function(user){
    if (user) {
        firebase.firestore().collection('users').doc(user.uid).get()
        .then(...)
    }
    //...
}
 

2。使用自定义声明

如果您只需要存储有限数量的额外信息来提供访问控制,您可以使用 Custom Claims 。这特别适合存储用户角色,例如付费用户。

自定义用户声明可通过用户的身份验证 token 访问,因此您可以使用它们根据用户的角色或访问级别修改客户端 UI。查看更多详情here在文档中。


要在前端获取声明,您可以执行以下操作:

firebase.auth().onAuthStateChanged(function (user) {
    if (user) {
        user.getIdTokenResult()
            .then((idTokenResult) => {
                // Confirm the user is a paid user.
                if (!!idTokenResult.claims.paidUser) {
                    // Show admin UI.
                    showPaidUserUI();
                } else {
                    // Show regular user UI.
                    showRegularUI();
                }
            })
            .catch((error) => {
                console.log(error);
            });
    }
    //...
}

请务必注意文档中的以下部分:

Custom claims are only used to provide access control. They are not designed to store additional data (such as profile and other custom data). While this may seem like a convenient mechanism to do so, it is strongly discouraged as these claims are stored in the ID token and could cause performance issues because all authenticated requests always contain a Firebase ID token corresponding to the signed in user.

  • Use custom claims to store data for controlling user access only. All other data should be stored separately via the real-time database or other server side storage.
  • Custom claims are limited in size. Passing a custom claims payload greater than 1000 bytes will throw an error.

关于firebase - 将数据保存到 Firebase 用户对象中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60704394/

相关文章:

ios - 将快照字典从 firebase 数据库保存到类对象

firebase - 一段时间后删除 Firebase 匿名用户

java - 从 Firebase 实时数据库获取当前用户信息

java - Firebase Auth - 复制修改后的用户登录名/电子邮件

firebase - Flutter Firebase Auth 返回null,然后返回正确的值

Travis 上的 Firebase 部署错误

android - 有没有办法从 firebaseauth 获取名字和姓氏?

flutter - getter 'email'在null-Flutter/Firebase上被调用

javascript - ref 内的代码一旦不执行 angularjs

c# - Firebase Unity 插件 : How do you persist user session?(自动登录)