6

I am building a React Native app which uses Firebase phone authentication for user login. Authentication works fine but the token expires after an hour. I have read that I need to use the refresh token to refresh the idToken, but nowhere on the Firebase docs does it explain how to do this. It only explains how to revoke refresh tokens, and I can't even find it.

I am using the react-native-firebase package.

My questions are: how to I get the refresh token, how do I use it, and do I really need to call Firebase every hour to update my idToken?

I am currently getting my idToken like this:

const authenticate = async (credential) => {
  try {
    const { user } = await firebase.auth().signInWithCredential(credential);
    const accessToken = await user.getIdToken();
    return accessToken;
  } catch (error) {
    console.log(error);
  }
}

I then take the token and store it locally using AsyncStorage and check if the token exists every time the app is launched.

Thanks in advance.

Mr. Robot
  • 1,334
  • 6
  • 27
  • 79

1 Answers1

7

From https://rnfirebase.io/reference/auth/user#getIdToken It seems that using user.getIdToken() refresh the token if it has expired. You can always use the forceRefresh option if you want to refresh the token even if it's still valid.

Onlinogame
  • 973
  • 6
  • 12
  • 1
    Thank you - at the moment I am using `user.getIdToken` to get the initial token, but to get the `user` object I have to pass the `verificationId` and `smsCode` to get the `credential` and then the `credential` to `firebase.auth().signInWithCredential(credential)` to get the `idToken`. What's the best way of simply refreshing the token? I have built some logic to store the credential to `AsyncStorage` and using it when the token has expired but not sure if that's the best approach. – Mr. Robot Aug 20 '19 at 10:50
  • 2
    With the IdToken being refreshed automatically, you just need to use user.getIdToken() with the credential before any API call. The credentials are persistent, it means that to get it (even after app restart), you need to call `firebase.auth().onAuthStateChanged((user) => ...)` to get it, You don't need to store the credentials in the ***AsyncStorage*** – Onlinogame Aug 20 '19 at 11:53
  • 1
    Thanks @OnlinoGame! So does this mean I should never need to store the `idToken` in `AsyncStorage` because they are always persistent? I just call the function? And also do you know why the `onAuthStateChanged` method does not return a promise? – Mr. Robot Aug 20 '19 at 12:40
  • 2
    onAuthStateChanged use a callback instead. `firebase.auth().onAuthStateChanged(function(user) { if (user) { // User is signed in. } else { // No user is signed in. } });` And no you won't need AsyncStorage – Onlinogame Aug 20 '19 at 15:04