如何使用Javascript在Firestore中验证用户的ID令牌? [英] How to verify a user's ID token in firestore using Javascript?

查看:34
本文介绍了如何使用Javascript在Firestore中验证用户的ID令牌?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在构建一个本机应用程序,并使用Firebase(更具体地说是firestore)来管理我的数据.我当前的目标是在我的应用程序上实现自动登录功能,如果用户退出应用程序,我希望他们保持登录状态,除非他们在退出应用程序之前手动点击 Signout 按钮.这是我目前执行此操作的过程:

I am building a react native application and am using Firebase, more specifically firestore, in order to manage my data. My current objective is to implement an auto login feature on my app, where if the user exits the app, I want them to stay signed in, unless they manually hit the Sign Out button before exiting the app. Here is my current process of doing this:

当用户登录该应用程序时,我通过以下方式登录: firebase.auth().signInWithEmailAndPassword(电子邮件,密码).然后,我通过以下方式获取其idToken:

When the user logs into the app, I sign them in by: firebase.auth().signInWithEmailAndPassword(email, password). I then get their idToken by:

  let authIdToken = "";
  firebase
    .auth()
    .currentUser.getIdToken(true)
    .then(function (idToken) {
      authIdToken = idToken
    })
    .catch(function (error) {
      console.log(error)
    });

然后我想将此令牌保存到手机中,因此当用户再次打开应用程序时,我可以获取此令牌并检查其有效性.如果有效,那么我可以使用其idToken登录用户.在本机反应中,我可以这样做:

I then want to save this token into the phone, so when the user opens the app again, I can fetch this token and check its validity. If it is valid, then I can log the user in using their idToken. In react native, I can do this by doing:

AsyncStorage.setItem(
    "userData",
    JSON.stringify({
      token: token,
    })
  );

现在,当应用加载时:

const startScreen = props => {
   useEffect(() => {
    const tryLogin = async () => {
     const userData = await AsyncStorage.getItem("userData");
     const transformedData = JSON.parse(userData);
     const { token } = transformedData;

     await firebase
       .auth()
       .verifyIdToken(token, true)
       .then((payload) => {
         console.log(true)
       })
       .catch((error) => {
         if (error.code == "auth/id-token-revoked") {
           // Token has been revoked. Inform the user to reauthenticate or signOut() the user.
           console.log("revoked")
         } else {
           console.log("error")
         }
       });
    };
    tryLogin();
 }, []);

问题::当我尝试以此方式验证令牌时,遇到以下错误: firebase.auth().verifyIdToken不是函数.我通读了文档,不确定如何使用JS验证此令牌.我该如何验证?让我知道我的验证过程是否不正确以及应如何进行.我是刚开始使用Firestore和进行身份验证的新手,并希望学习正确的方法.

The Issue: When I try to verify the token this way, I am met with the following error: firebase.auth().verifyIdToken is not a function. I read through the documentation and am unsure of how else to verify this token using JS. How do I verify it? Let me know if my verification process is incorrect and how it should be done. I am new to using firestore and doing authentication in general and hope to learn how to do it the right way.

另一个有用的说明:这是我配置Firestore的方式:!firebase.apps.length?firebase.initializeApp(firebaseConfig):{};

Another helpful note: This is how I am configuring my firestore: !firebase.apps.length ? firebase.initializeApp(firebaseConfig) : {};

谢谢!

推荐答案

然后我想将此令牌保存到手机中,因此当用户再次打开应用程序时,我可以获取此令牌并检查其有效性.

I then want to save this token into the phone, so when the user opens the app again, I can fetch this token and check its validity.

这完全没有必要.具有永久登录帐户的Firebase Auth,无需执行任何操作即可自动刷新令牌.您需要做的就是聆听令牌更新的可用时间,并根据需要对新令牌进行操作.您可以使用 onIdTokenChanged 建立ID令牌侦听器显示在链接的API文档中:

This is completely unnecessary. Firebase Auth with persist the signed in user, and automatically refresh the token without you having to do anything. All you need to do is listen to when updates to the token are made available, and act on the new token as needed. You can establish an ID token listener using onIdTokenChanged as shown in the linked API documentation:

firebase.auth().onIdTokenChanged(function(user) {
  if (user) {
    // User is signed in or token was refreshed.
  }
});

有了此令牌后,您就知道用户已成功登录.无需执行任何操作.无需使用它登录.

Once you have this token, you know that the user is successfully signed in. There is nothing left to do. There is no need to use it to sign in.

此外,您无法在前端上验证令牌.您正在查看的 verifyIdToken 方法仅适用于Admin SDK,该方法仅在后端运行.想法是,您在令牌上获得令牌,然后按照管理SDK的文档.后端使用它来安全地确定前端用户是否是他们所说的人.

Also, you can't verify the token on the frontend. The verifyIdToken method you're looking at is for the Admin SDK only, which only runs on the backend. The idea is that you get the token on the fronend, then pass it to the backend as described in the documentation for the Admin SDK. The backend uses this to securely determine if the user on the frontend is who they say they are.

由于您没有说是否有后端,因此根本不需要处理此令牌.如果您只想知道用户何时登录(即使他们离开后才返回页面,那么您可以跳过上面的所有内容,而只需使用

Since you didn't say if you have a backend or not, dealing with this token might not be necessary at all. If you just want to know when the user is signed in (even if they are just returning to the page after being away, then you can skip everything above and just use an auth state observer. Again, Firebase Auth persists information about the user so you don't have to sign them in again. The observer will tell you when the automatic sign-in is complete, or if they are not signed in at all.

这篇关于如何使用Javascript在Firestore中验证用户的ID令牌?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆