简体   繁体   English

如何使用 Javascript 在 Firestore 中验证用户的 ID 令牌?

[英]How to verify a user's ID token in firestore using Javascript?

I am building a react native application and am using Firebase, more specifically firestore, in order to manage my data.我正在构建一个反应本机应用程序,并且正在使用 Firebase,更具体地说是 firestore,来管理我的数据。 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.我目前的目标是在我的应用程序上实现自动登录功能,如果用户退出应用程序,我希望他们保持登录状态,除非他们在退出应用程序之前手动点击Sign Out按钮。 Here is my current process of doing this:这是我目前执行此操作的过程:

When the user logs into the app, I sign them in by: firebase.auth().signInWithEmailAndPassword(email, password) .当用户登录应用程序时,我通过以下方式登录: firebase.auth().signInWithEmailAndPassword(email, password) I then get their idToken by:然后我通过以下方式获取他们的 idToken:

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

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.如果它有效,那么我可以使用他们的 idToken 登录用户。 In react native, I can do this by doing:在本机反应中,我可以这样做:

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

Now when the app loads up:现在当应用程序加载时:

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();
 }, []);

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.问题:当我尝试以这种方式验证令牌时,遇到以下错误: firebase.auth().verifyIdToken is not a function. I read through the documentation and am unsure of how else to verify this token using JS.我通读了文档,不确定如何使用 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 和一般进行身份验证,并希望学习如何以正确的方式进行。

Another helpful note: This is how I am configuring my firestore: .firebase.apps?length. firebase:initializeApp(firebaseConfig); {};另一个有用的说明:这是我配置 Firestore 的方式: .firebase.apps?length. firebase:initializeApp(firebaseConfig); {}; .firebase.apps?length. firebase:initializeApp(firebaseConfig); {};

Thanks!谢谢!

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.然后我想将此令牌保存到手机中,这样当用户再次打开应用程序时,我可以获取此令牌并检查其有效性。

This is completely unnecessary.这是完全没有必要的。 Firebase Auth with persist the signed in user, and automatically refresh the token without you having to do anything. Firebase 使用持久登录用户进行身份验证,并自动刷新令牌,而无需您执行任何操作。 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:您可以使用onIdTokenChanged建立 ID 令牌侦听器,如链接的 API 文档中所示:

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.无需使用它来登录。

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.您正在查看的verifyIdToken方法仅适用于仅在后端运行的 Admin SDK。 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 .这个想法是您在前端获取令牌,然后按照 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.如果您只想知道用户何时登录(即使他们只是在离开后返回页面,那么您可以跳过上面的所有内容,只需使用身份验证 state 观察者。同样,Firebase 身份验证会保留有关用户的信息,因此您不必再次登录。观察者会在自动登录完成时告诉您,或者他们是否根本没有登录。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何使用PHP验证用户的Google令牌ID? - How can I verify user's Google Token ID with PHP? Instagram如何使用JavaScript从访问令牌中获取用户ID? - Instagram how to get user id from access token using javascript? 如何在sharepoint中使用Javascript验证登录用户 - How to verify the logged in user using Javascript in sharepoint 使用javascript验证ID号 - Verify ID Number using javascript 如何使用javascript中的复选框获取每个成员的用户ID(user_id)? - How to get user's id (user_id) of each member using a checkbox in javascript? 如何在加载 dom 之前验证用户令牌? - How to verify user token before the dom is loaded? 如何使用Javascript添加事件监听器来验证用户输入? - How to verify user input using Javascript add Event Listener? 如何在服务器端(Node.js)以编程方式验证Facebook用户的访问令牌? - How to verify a Facebook user's access token programmatically on the server-side (Node.js)? 使用 Firestore collections 时等待用户 ID - Wait for user id when using firestore collections 使用谷歌登录无法从 firebase 获取“电子邮件”验证 id 令牌 - Not getting "email" from firebase verify id token using google sign in
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM