13

I'm makeing tests with Firebase Authentication from javascript client and I'm trying to retrieve the idToken with retrieve id tokens on clients documentation

I think I'm forgetting something basic.

A user is logged in with Google

The code is just i've seen in other posts and in the documentation. And the result is in the comments.

firebase.auth().onAuthStateChanged(function(user) {
  if (user) {
     console.log(user); // this is shown. Firebase user and provider data
     console.log(user.uid); // Shown
        firebase.auth().user.getIdToken().then(function(idToken) {
           console.log(idToken+'--'); // Nothing happens. No errors and the function not continues
        });
     console.log(user.uid); // Nothing happens
  }
})

Thanks

EDIT:

if I add anything wrong nothing happens too. for example if I add an alert it shows the alert but if I have a mistake, for example alter() not shows any error. Added catch and nothing too

firebase.auth().onAuthStateChanged(function(user) {
  if (user) {
     alter() // Nothing happens and the function stop         
     console.log(user); // this is shown. Firebase user and provider data
     console.log(user.uid); // Shown
        firebase.auth().user.getIdToken().then(function(idToken) {
           console.log(idToken+'--'); // Nothing happens. No errors and the function not continues
        }).catch(function(error) {
            console.log(error+'--'); // Nothing
        });
     console.log(user.uid); // Nothing happens
  }
})
Luis Gar
  • 457
  • 1
  • 4
  • 18
  • 3
    According to the docs, it's `firebase.auth().currentUser.getIdToken()`, not `firebase.auth().user` like you have here. Try that and see if it fixes it, and if not, update your question – kingdaro Apr 08 '18 at 20:32
  • Tried. Same result. I got the code from other post and they say worked. And the same with this one. https://stackoverflow.com/questions/39799588/finding-correct-firebase-auth-id-token-on-onauthstatechanged – Luis Gar Apr 08 '18 at 20:40

3 Answers3

21

firebase.auth().user doesn't have the user in that moment yet. You have to use the user from firebase.auth().onAuthStateChanged directly like this:

firebase.auth().onAuthStateChanged(function(user) {
    if (user) {
        console.log(user); // It shows the Firebase user
        console.log(firebase.auth().user); // It is still undefined
        user.getIdToken().then(function(idToken) {  // <------ Check this line
           console.log(idToken); // It shows the Firebase token now
        });
    }
});

You can only use firebase.auth().user after firebase.auth().onAuthStateChanged is completed and outside of its scope, otherwise it will be undefined.

  • the fat arrow version... user.getIdToken().then((idToken) => { console.log(idToken); }); – sigmapi13 Jan 06 '20 at 12:16
  • I'm getting this error `[Error: [auth/internal-error] An internal error has occurred, please try again.]` when using this `await auth().currentUser?.getIdToken(true)` "@react-native-firebase/app": "12.4.0", "@react-native-firebase/auth": "12.4.0", – ruin3936 Nov 10 '21 at 03:06
  • How can I get this token while making API calls? – backslashN May 07 '23 at 05:13
0

firebase.auth().currentUser is synchronous. We can make it asynchronous by subscribing to the auth observable instead.

Depending on the library we’re using, the JavaScript SDK has onAuthStateChanged() and AngularFire2 has both authState() onAuthStateChanged().

// For AngularFire:

private afAuth: AngularFireAuth,

afAuth.authState.subscribe(user => {
  if (user) {
    user.getIdToken(true).then(idToken => {
      // ...
    });
  }
});

// or

this.afAuth.auth.onAuthStateChanged(user => {
  if (user) {
    user.getIdToken(true).then(idToken => {
     //...
    });
  }
});



// For the JS SDK
firebase.auth().onAuthStateChanged(user => {
  if (user) {
    user.getIdToken(true).then(idToken => {
      // ...
    });
  }
});
i.karayel
  • 4,377
  • 2
  • 23
  • 27
0

For firebase versions greater than V8. We directly have to call the functions of auth.

const loginWithGoogle = () => {
const googleProvider = new GoogleAuthProvider();
signInWithPopup(auth, googleProvider)
  .then((userCredentials) => {
    if (userCredentials) {
      setIsUserAuthenticated(true);
      window.localStorage.setItem('authorization', true);
      console.log(userCredentials);
      userCredentials.user.getIdToken().then((token) => {
        setToken(token);
        console.log(token);
      });
    }
  })
  .catch((err) => {
    console.log(err.message);
  });
};

Check out @prograamer on YouTube for top-notch programming tutorials! Subscribe now for the latest videos and related content: https://www.youtube.com/@prograamer?sub_confirmation=1.

Aamer
  • 417
  • 3
  • 9