Agares
Agares

Reputation: 59

How to get user ID token changes from Firebase Auth on Flutter

I'm developing a Flutter app using Firebase Auth and for the backend AdonisJS, I already created the sign up/sign in methods, the problem/dude that I have is that the firebase auth token expires after 1 hour and I don't know the correct way to get the new token to send it to the backend to know if the user it authorized to the REST API.

I know I can get the new token with

await _firebaseAuth.currentUser.getIdToken()

But how should I check if the token expired and if so, how to ask for the new one? Is there something like a daemon to check it every time I'm going to consume my REST API

Your help is really appreciated, I'm pretty new to Firebase and Flutter

Upvotes: 1

Views: 4436

Answers (2)

Doug Stevenson
Doug Stevenson

Reputation: 317342

If you want updates to the ID token as it gets automatically refreshed every hour by the Firebase Auth SDK, the documentation briefly explains how to do that:

If you need authentication state change events along with any user token refresh events, you can subscribe via the idTokenChanges() method instead.

It works similar to the authStateChanges() stream in the code provided just above that text. It will look something like this:

FirebaseAuth.instance
  .idTokenChanges()
  .listen((User user) {
    if (user == null) {
      print('User is currently signed out!');
    } else {
      user.getIdToken().then((String token) {
        print('The user ID token is' + token);
      })
    }
  });

You can store the token globally and use it as much as you want. Assuming that this stream keeps putting the new token in that global space, you should not have any problems reusing it.

Upvotes: 2

Fabio Lopez
Fabio Lopez

Reputation: 527

With firebase there's no need to store the token and to manage it manually. the web API already manages the session for you and lets you know when there's a change of authorization or login state.

You can see how to implement that last mentioned listener here

If you need to verify if the token is valid in your back end, there's a section in the Node admin SDK where you can check the token.

Finally, to retrieve the newest possible token, you can use the method you mentioned like this:

firebase.auth().currentUser.getIdToken(/* forceRefresh */ true)

Upvotes: 3

Related Questions