Auto refreshing firebase authentication without a window reload?

Viewed 56

I'm trying to work out why my JWT keeps expiring and the refresh doesn't appear to work, the crux of my code handling this:

React.useEffect(() => {
    firebase.auth().onAuthStateChanged(async (auth) => {
        if (auth) {
            const token = await auth.getIdToken();
            setToken(token)
            nookies.destroy({}, "token");
            nookies.set({}, "token", token, {
                path: "/"
            });

            setAuth(auth);

            const val = jwt_decode(token) as any;
            const exp = Number(val.exp);

            let timeToExpiry = moment(exp * 1000 - 1000 * 5).diff(moment());
            const updateToken = () => {
                setTimeout(async () => {
                    console.log("REFRESHING TOKEN");
                    await firebase.auth().currentUser.getIdToken(true).then(c => {
                        setToken(c);
                        const val = jwt_decode(c) as any;
                        const exp = Number(val.exp);
                        timeToExpiry = moment(exp * 1000 - 1000 * 5).diff(moment());
                        //alert("refreshing "  + timeToExpiry);
                        //console.log(timeToExpiry + " DONE REFRESHING TOKEN");
                        updateToken();
                    });
                }, timeToExpiry)
            }
            updateToken();
        }
        else {
            setToken("");
            nookies.destroy({}, "token");
            setAuth(null);

            var provider = new firebase.auth.GoogleAuthProvider();
            provider.setCustomParameters({
                prompt: 'select_account'
            });

            firebase.auth().signInWithRedirect(provider);
        }
    })
}, [])

The timeout works and it calls the getIdToken() before expiry HOWEVER the very next request still errors out with JWT token expired requiring me to refresh the window which actually fixes it.

Is there any way to get these tokens to refresh without doing refreshing the window?

1 Answers

The onAuthStateChanged only fires when a user's authentication state change, so when they're logged in or logged out.

If you want to get updates to the ID token, listen to the onIdTokenChanged event.

Related