【问题标题】:Firebase .getIdToken() returns invalid tokenFirebase .getIdToken() 返回无效令牌
【发布时间】:2021-07-06 19:21:59
【问题描述】:

我正在尝试使用电子和 firebase 重定向制作一个简单的身份验证应用程序,但是如果用户已经登录并且我使用 firebase.auth().currentUser.getIdToken() 来获取该用户的 IdToken,但是当我尝试使用该令牌时 firebase.auth().signInWithCredential(credential) 我收到错误消息 ERROR: auth/invalid-credential

这是我的代码前端

firebase.auth().onAuthStateChanged( async function (user) {
if (user) {
  // User is signed in.
  var user = await firebase.auth().currentUser;

  if (user != null) {
     await firebase.auth().currentUser.getIdToken().then(function(idToken) {
       window.location.href = "electron://"+idToken;
     }).catch(function(error) {
       console.log(error)
     });
    

  }

} else {
  // No user is signed in.
  document.getElementById("user_div").style.display = "none";
  document.getElementById("login_div").style.display = "block";

}
});

这是我的代码后端

app.on('second-instance', (event, commandLine, workingDirectory) => {
    if (commandLine[2]) {
      var url = commandLine[2].split('/')
      var id_token = url[2]
      console.log('id: ', id_token)

      // Build Firebase credential with the Google ID token.
      var credential = firebase.auth.GoogleAuthProvider.credential(id_token);
      // Sign in with credential from the Google user.
      firebase.auth().signInWithCredential(credential)
      .then((success)=>{
        myWindow.loadFile('./scr/welcome.html')
        console.log('RESULT: ',success)
      })
        .catch((error) => {
          // Handle Errors here.
          var errorCode = error.code;
          var errorMessage = error.message;
          console.log('ERROR:', errorMessage)
          // The email of the user's account used.
          var email = error.email;
          // The firebase.auth.AuthCredential type that was used.
          var credential = error.credential;
          console.log('ERROR:', credential)
          // ...
        })
      
    }

我错过了什么或做错了什么?

【问题讨论】:

    标签: javascript firebase firebase-authentication


    【解决方案1】:

    这不是 ID 令牌的工作方式。 ID 令牌的目的是传递给您的后端,以便它可以验证登录用户的身份,并代表他们执行一些操作。再次登录客户端无效。您可能需要查看documentation on use of ID tokens 以了解其工作原理。

    signInWithCredential 仅在您正确构建 GoogleAuthProvider 凭据时才能与 Google Auth 一起使用。 API documentation 中有很多示例代码。

    【讨论】:

    • 哦,我明白了,我会检查文档,看看它是如何工作的,谢谢!!
    • 我现在可以使用 admin SDK,再次感谢您的解释!