invertase / react-native-firebase

🔥 A well-tested feature-rich modular Firebase implementation for React Native. Supports both iOS & Android platforms for all Firebase services.
https://rnfirebase.io
Other
11.63k stars 2.2k forks source link

Token expiration issue. Would I need to manually handle the token refresh after expiration #7900

Closed don-007 closed 3 weeks ago

don-007 commented 1 month ago

I am using Firebase in frontend & backend for authentication. Since it has an expiraton of 1 hour. After using the application continusously for 1 hour. When I hit the BE API then it fails since it has expired according to Backend. But Frontend doesn't know that it has expired & does'nt refresh automatically. Is there any default fucntionality provided by Firebase for this use-case. But oAuthStateChange should trigger when the token has expired right ?

This is how I have my code. Am I missing anything. Can someone please help here


  useEffect(() => {
    const unsubscribe = onAuthStateChanged(auth, async (currentUser) => {
      await updateAccessToken(currentUser);
    });
    return () => unsubscribe();
  }, [user]);

  const updateAccessToken = async (
    updatedUser = user,
    forceRefresh = false,
  ) => {
    try {
      const token = await updatedUser?.getIdTokenResult(forceRefresh);
    } finally {
          // Some logic here
    }
  };

So how do I refresh the token automatically as when using the application itself the token expires & the backend is keep on throwing "Not logged in" error. Ideally onAuthStateChanged should be triggered on Token expiration I hope... Someone please throw some light in here for me.... Thanks in advance

Lyokone commented 1 month ago

Hello @don-007, your code seems correct. Would you be able to provide a full reproduction example so we can check what is happening?

RohovDmytro commented 1 month ago

I am investigation an issue when getting token fails on Amazon tablets.

I'm a bit lost. Is it expected to update token manually by the developer every hour or is it something that should happen automatically?

russellwheatley commented 3 weeks ago

The authStateChanged API is called when the user signs-in/signs-out, that's it. It does not trigger when the token is invalidated. To ensure your token is valid, you can call this method which will tell you when it expires.

If required, you ought to refresh your token before making api calls to your backend. Hope this helps.