首页 > 解决方案 > Firebase signInWithCustomToken 未过期?

问题描述

我觉得问这个很愚蠢,但我还是要问

我在 firebase 中还是新手,现在尝试使用 signInWithCustomToken 以管理员身份编辑我的用户数据这是我的 firebase 数据库实时规则

{
          "rules": {
            ".read": "auth != null",
            "users": {
              "$user_id": {
                ".read": true,
                ".write": "$user_id == auth.uid"
              }
            }
          }
        }

这是我的客户端(?)代码,我使用 ajax 将用户名和密码发送到 CI 控制器,然后控制器从那里将值发送到 nodejs

    $.ajax({
        type: "POST",
        url: "Umum/senddata/"+user+"/"+pass
        }).done(function( msg ) {
            firebase.auth().signInWithCustomToken(msg).catch(function(error) {
                  // Handle Errors here.
                  var errorCode = error.code;
                  var errorMessage = error.message;
                  if (errorCode === 'auth/invalid-custom-token') {
                    alert('The token you provided is not valid.');
} else {
                                console.error(error);
                                }
                            });
                        }) 

                    }); 

这是我的节点 js 代码。首先我需要检查用户名是否存在于firebase中,然后我将获取UID来创建customtoken,然后将customtoken发送回客户端

app.post('/sendata', function(req, res) {
    var content = req.body;
    admin.database().ref('/admins').orderByChild('username').equalTo(content.username).once('value').then(function(snapshot) {
        snapshot.forEach(function(childSnapshot) {

            admin.auth().createCustomToken(childSnapshot.val().adminuid).then(function(customToken) {
                console.log("customtoken : " + customToken);
                //to-do: forward the message to the connected nodes.
                res.end(customToken);
                admin.auth().verifyIdToken(customToken).then(function(decodedToken) {
                    var uid = decodedToken.uid;
                    console.log("uidnya : " + uid);
                    // ...
                }).catch(function(error) {
                    // Handle error
                });
            }).catch(function(error) {
                console.log("Error creating custom token:", error);
            });
        });
    });
});

现在的问题是,人们说令牌将在 1 小时内到期。他们所说的过期是什么意思?过期后他们不能编辑用户数据还是什么?因为我的仍然可以工作,即使在 1 小时后无需重新登录,我仍然能够编辑我的用户数据。或者我的 signInWithCustomToken 是错误的?但我试图 console.log 并返回正确的用户我用来登录如果令牌过期会发生什么?

标签: firebasefirebase-admin

解决方案


您将自定义令牌与 ID 令牌混淆了。

您返回给客户端的自定义令牌会在一小时后过期。通常这很好,因为您只需要使用一次signInWithCustomToken. 这将在客户端登录用户。作为交换,Firebase 身份验证服务器将返回 Firebase ID 令牌和刷新令牌并存储在客户端上(Firebase ID 令牌用于检查用户是否经过身份验证并访问诸如 Firebase 实时数据库/Firestore/等之类的东西)。这就是你所呼吁verifyIdToken的。Firebase ID 令牌将在一小时后过期,但 Firebase 刷新令牌将允许客户端刷新该 ID 令牌。


推荐阅读