Skip to content

Firebase .getIdToken() returns invalid token

I’m trying to make just a simple authentication app with electron and firebase redirect, but if the user is already logged in and I use the firebase.auth().currentUser.getIdToken() to get the IdToken of that user, but when i try that token in firebase.auth().signInWithCredential(credential) I get the error that says ERROR: auth/invalid-credential

Here is my code front-end

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";

}
});

Here is my code back-end

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)
          // ...
        })
      
    }

I’m missing something or doing something wrong?

Answer

That’s not how ID tokens work. The purpose of an ID token is to pass to your backend, so that it can validate the identity of the signed in user, and perform some action on their behalf. It’s not valid for signing in on the client again. You might want to review the documentation on use of ID tokens to learn how this works.

signInWithCredential only works with Google Auth when you correctly construct a GoogleAuthProvider credential. There is plenty of sample code in the API documentation for that.