How to get ID token refreshed when using Firebase Auth javascript SDK

Viewed 56

I use a backend app server to communicate with firestore, so the ReactJS client sends ID token to server which in turn communicates with firebase using that token. Client does not make any firebase calls directly other than auth calls. Problem I am facing is, the ID token never gets refreshed and after an hour, backend server fails to recognize token and ends up sending 401 to client. My understanding is that the client should always refresh the token and always send a valid token to backend app server.

firebase.auth().onAuthStateChanged(auth, (user) => {
    if (user) {
        localStorage.setItem("auth.uid", user.uid)
        localStorage.setItem("auth.email", user.email)
        user.getIdToken(true).then(function(idToken) {
            localStorage.setItem("auth.token", idToken)
        })
    } else {
        // User is signed out
        localStorage.removeItem("auth.email")
        localStorage.removeItem("auth.uid")
        localStorage.removeItem("auth.token")
    }
})

firebase.auth().onIdTokenChanged((user) => {
    // ** NOT GETTING THIS CALLBACK AFTER 1 HR TO REFRESH **
    if (user) {
        // User is signed in or token was refreshed
        user.getIdToken(true).then(function(idToken) {
            localStorage.setItem("auth.token", idToken)
        })
    }
})

Other option, may be, is to use the REST API to manually fetch a new ID token and use that but having passed forceRefresh value true I would expect this is handled automatically.

What am I missing?

0 Answers
Related