首页 > 解决方案 > Firebase .getIdToken() 返回无效令牌

问题描述

我正在尝试使用电子和 firebase 重定向制作一个简单的身份验证应用程序,但是如果用户已经登录并且我使用 firebase.auth().currentUser.getIdToken()来获取该用户的 IdToken,但是当我尝试使用该令牌时, firebase.auth().signInWithCredential(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)
          // ...
        })
      
    }

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

标签: javascriptfirebasefirebase-authentication

解决方案


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

signInWithCredential仅当您正确构建 GoogleAuthProvider 凭据时才适用于 Google Auth。API 文档中有大量示例代码。


推荐阅读