Search code examples
javascriptreact-nativefirebase-authenticationredux-sagaauth-token

Firebase ID Token expiration in an hour


so I am using redux-saga in my react-native app and tried to use refresh token but didn't work, so my approach was the following in app.js in order to get the token specifically for each request and force refresh it:

  handleResponse = async () => {
    const {dispatch} = this.store;
    await axios.interceptors.request.use(config => {
      // Important: request interceptors **must** return the request.
      console.log("refreshToken")
      let user =  firebase.auth().currentUser;
        firebase.auth().onAuthStateChanged(function(user) {   if (user) {
          console.log("auth changed: ",user)
          user.getIdToken(true).then((token) => {
                setAccessToken(token);
                config.headers.authorization = token;
              }
          );
        } else { console.log("didn't auth change") } });
      console.log("req in handle response: ",JSON.stringify(config));
      return config;
    });
    axios.interceptors.response.use(config => config, (err) => {
      if (err.response) {
        const response = err.response;
        const state = this.store.getState();
        if (
            response.status === 401
            && state.auth.isAuthenticated
        ) {
          dispatch(logout());
        }
      }
      return Promise.reject(err);
    });
  };

But it always ends up after an hour throwing me the following error::

Firebase ID token has expired. Get a fresh token from your client app and try again (auth/id-token-expired). See https://firebase.google.com/docs/auth/admin/verify-id-tokens for details on how to retrieve an ID token.

so I was wondering if there's another approach I can try to solve the issue from my side?

Thanks in advance.


Solution

  • Firebase auth tokens automatically refresh every hour. That's a function of the SDK, and you don't have to do anything to enable it.

    You definitely do not want to call firebase.auth().onAuthStateChanged for each request. That starts a persistent listener, and adds a new callback every time it's used. Typically you add just one listener globally for your app, and use its updates as they happen.

    If you need to know when the SDK refreshes the token in order to get a new one immediately, you should instead use onIdTokenChanged to set up a callback that will be invoked every time the user's token changes. Again, you should only set up one of these globally for your app, and use its current value at the time of the request.