Firebase Rest API Authentication ID Token And Token Refresh In React Native

Firebase Official docs says that Firebase Token ID of a user expires in 1 hour . to generate a new token refresh token id is to be passed to an end point where in response the client receives new token id .

So question is that to keep a persistent Loged in behaviour in my react native app while user is not using app in foreground for hours would i have to start a background service that refreshes Firebase Token ID after every hour? or is their a better and easy way to keep firebase token id for users refreshed and keep user loged in.



Firebase Auth State Persistence (recommended)

The Firebase web API provides the following options for Authentication State Persistence:

  • local: Indicates that the state will be persisted even when the browser window is closed or the activity is destroyed in React Native. An explicit sign out is needed to clear that state. Note that Firebase Auth web sessions are single host origin and will be persisted for a single domain only.
  • session: Indicates that the state will only persist in the current session or tab, and will be cleared when the tab or window in which the user authenticated is closed. Applies only to web apps.
  • none: Indicates that the state will only be stored in memory and will be cleared when the window or activity is refreshed.

Using the Firebase state persistence API directly is by far the most straight forward solution.

However, if you are set on implementing state persistence from scratch using the Firebase Admin SDK, then you could do the following.

Custom State Persistence (not recommended)

  1. User signs in.
  2. The Firebase user ID and a secret token generated by the server are saved in storage, for example, React Native AsyncStorage. The secret token is also stored in a database.
  3. While the app is running, refresh tokens are periodically retrieved to keep the session live.
  4. User closes the app.
  5. User opens the app.
  6. App checks storage for the Firebase user ID and the secret token. If found, these are sent to the server to confirm if the secret code matches the code stored in the database.
  7. If the secret code matches, the server then generates a custom auth token based on the Firebase user ID and sends back to the React Native app.
  8. The React Native app automatically signs in the user with the custom auth token.