Ilja
Ilja

Reputation: 46479

Unable to trigger re-authentication with firebase v4, javascript

I was previously able to trigger onAuthStateChanged without needing to sign user out after they verified their email using these methods called one after another.

firebase.auth.currentUser.reload()
firebase.auth.currentUser.getToken(true)

I updated them to getIdToken

firebase.auth.currentUser.reload()
firebase.auth.currentUser.getIdToken(true)

However with v4 of firebase previous and new approach are not re-triggering onAuthStateChange anymore. Is there a way to still achieve it now? i.e. for sign up flow where user doesn't need to log out -> signs up -> verifies email -> clicks "Continue" button that calls 2 functions above -> onAuthStateChanged get's triggered with user email now being verified.

Upvotes: 2

Views: 779

Answers (1)

Frank van Puffelen
Frank van Puffelen

Reputation: 598740

In version 2.x of Firebase Authentication, the auth state changed handler was only invoked when the user's authentication state changed. So when they signed in or out.

In version 3.x of the Firebase Authentication SDK, the same callback was also invoked for token refreshes. But this lead to developers having problems efficiently updating their UI, since this callback would be invoked even when the authentication state didn't change (even though the token did).

That's why this behavior has indeed changed in v4: the onAuthStateChanged doesn't fire anymore for token refreshes. There is a separate onIdTokenChanged() method that does fire in that case: https://firebase.google.com/docs/reference/js/firebase.auth.Auth#onIdTokenChanged

From there:

Adds an observer for changes to the signed-in user's ID token, which includes sign-in, sign-out, and token refresh events. This method has the same behavior as firebase.auth.Auth#onAuthStateChanged had prior to 4.0.0.

Example:

firebase.auth().onIdTokenChanged(function(user) {
  if (user) {
    // User is signed in or token was refreshed.
  }
});

Upvotes: 5

Related Questions