How to increase the expiry time of the token generated when user logged in?

428 views
Skip to first unread message

Aman Singh

unread,
Feb 22, 2020, 10:51:48 AM2/22/20
to Firebase Google Group
When the user logged in then firebase admin sdk generates a token for that user which is valid only for 1 hour. After 1 hour that token expired, so is there any way so that we can increase the expiry time of that token.

I know we can achieve this by using refresh tokens but my issue here here is:- Refresh tokens can be generated from Admin SDK or Client SDK and how it will be generated.

Please revert to my problem as soon as possible as i am stuck on this for so long now.

Thank You

Aadmaa

unread,
Feb 22, 2020, 1:08:29 PM2/22/20
to Firebase Google Group
I do something like this on the the client side, from within a Saga. I don't use it for direct access to Firebase - just to allow the user to authenticate to a Node server. The Node server uses the token sent from the same front end to authenticate to Firebase through Firebase admin, and the user doesn't have to authenticate to two different services. You might have to approach it differently depending on your use case (Especially this question: is there an active Firebase client device?)

1. Client side
2. It just needs the currentUser object
3. You do need a way to run a background process

 while (true) {
        let token;
        try {
            token = yield currentUser.getIdToken(true);          
        } catch (error) {
            if (error.code === "auth/network-request-failed") {
                console.log("Unable to refresh login token due to connectivity at: ", (new Date()).toLocaleString());
                console.log("Retrying in one minute.");
                yield delay(1000 * 60);
                continue;
            } else {
                const retryMinutes = (2 ** (Math.min(retryCounter5)))  // Cap it at 32 minutes
                retryCounter = retryCounter + 1;
                console.log("Error refreshing login token at: ", (new Date()).toLocaleString())
                console.log(`Retrying in ${retryMinutes} minute(s).`)
                yield delay(1000 * retryMinutes * 60);
                continue;
            }
        }
        // Reset the retry counter
        retryCounter = 0;
        const jwt = jwtDecode(token);
        const expires_at = jwt.exp;
        const issued_at_time = jwt.iat;
        const delay_ms = (expires_at - issued_at_time) * 900;
        // Put the fresh token where it's needed:
        yield put(setUserToken(token));
        yield delay(delay_ms);
    }

Aman Singh

unread,
Feb 24, 2020, 11:32:05 AM2/24/20
to fireba...@googlegroups.com
I try to run above code on node js server something like this:- 

exports.getRefreshToken = function* getToken(reqres) {
    let retryCounter;
    while (true) {
        let token;
        try {
            token = yield firebase.auth().currentUser.getIdToken(true);
        } catch (error) {
            if (error.code === "auth/network-request-failed") {
                console.log(
                    "Unable to refresh login token due to connectivity at: ",
                    new Date().toLocaleString()
                );
                console.log("Retrying in one minute.");
                yield delay(1000 * 60);
                next();
            } else {
                const retryMinutes = 2 ** Math.min(retryCounter5); // Cap it at 32 minutes
                retryCounter = retryCounter + 1;
                console.log(
                    "Error refreshing login token at: ",
                    new Date().toLocaleString()
                );
                console.log(`Retrying in ${retryMinutes} minute(s).`);
                yield delay(1000 * retryMinutes * 60);
                next();
            }
        }
        // Reset the retry counter
        retryCounter = 0;
        const jwt = jwtDecode(token);
        const expires_at = jwt.exp;
        const issued_at_time = jwt.iat;
        const delay_ms = (expires_at - issued_at_time) * 900;
        // Put the fresh token where it's needed:
        yield put(setUserToken(token));
        yield delay(delay_ms);
    }
};

And i am calling this function like this:-
app.post("*/user/refresh-token/"FBAuth, (reqres=>
    getRefreshToken(reqres)
);
 Here FBAuth is the middleware for the user. I am not getting any refresh tokens while running this program. And i have enabled authentication also in postman using Bearer Token of the user.

Thank You
 
On Saturday, February 22, 2020 at 10:51:48 AM UTC-5, Aman Singh wrote:
When the user logged in then firebase admin sdk generates a token for that user which is valid only for 1 hour. After 1 hour that token expired, so is there any way so that we can increase the expiry time of that token.

I know we can achieve this by using refresh tokens but my issue here here is:- Refresh tokens can be generated from Admin SDK or Client SDK and how it will be generated.

Please revert to my problem as soon as possible as i am stuck on this for so long now.

Thank You

--
You received this message because you are subscribed to the Google Groups "Firebase Google Group" group.
To unsubscribe from this group and stop receiving emails from it, send an email to firebase-tal...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/firebase-talk/9cd651d2-57f9-4591-92f3-238d0377f191%40googlegroups.com.

Aman Singh

unread,
Feb 24, 2020, 11:32:09 AM2/24/20
to fireba...@googlegroups.com
This is error i am getting in my console:-

Check if request is authorized with Firebase ID token
>  Error while verifying Firebase ID token: FirebaseAuthError: Firebase ID token has expired. Get a fresh ID 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.
>      at FirebaseAuthError.FirebaseError [as constructor] (C:\Users\Aman\Desktop\Predicta_Project\Predicta-Cloud-Functions\functions\node_modules\firebase-admin\lib\utils\error.js:42:28)
>      at FirebaseAuthError.PrefixedFirebaseError [as constructor] (C:\Users\Aman\Desktop\Predicta_Project\Predicta-Cloud-Functions\functions\node_modules\firebase-admin\lib\utils\error.js:88:28)
>      at new FirebaseAuthError (C:\Users\Aman\Desktop\Predicta_Project\Predicta-Cloud-Functions\functions\node_modules\firebase-admin\lib\utils\error.js:147:16)
>      at C:\Users\Aman\Desktop\Predicta_Project\Predicta-Cloud-Functions\functions\node_modules\firebase-admin\lib\auth\token-verifier.js:199:39
>      at Object.module.exports [as verify] (C:\Users\Aman\Desktop\Predicta_Project\Predicta-Cloud-Functions\functions\node_modules\jsonwebtoken\verify.js:126:14)
>      at C:\Users\Aman\Desktop\Predicta_Project\Predicta-Cloud-Functions\functions\node_modules\firebase-admin\lib\auth\token-verifier.js:191:17
>      at new Promise (<anonymous>)
>      at FirebaseTokenVerifier.verifyJwtSignatureWithKey (C:\Users\Aman\Desktop\Predicta_Project\Predicta-Cloud-Functions\functions\node_modules\firebase-admin\lib\auth\token-verifier.js:190:16)
>      at C:\Users\Aman\Desktop\Predicta_Project\Predicta-Cloud-Functions\functions\node_modules\firebase-admin\lib\auth\token-verifier.js:175:30
>      at processTicksAndRejections (internal/process/task_queues.js:93:5) {
>    errorInfo: {
>      code: 'auth/id-token-expired',
>      message: 'Firebase ID token has expired. Get a fresh ID 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.'
>    },
>    codePrefix: 'auth'
>  }

Hiranya Jayathilaka

unread,
Feb 25, 2020, 1:55:02 PM2/25/20
to fireba...@googlegroups.com
Hi Aman,

There's no way to extend the lifespan of an ID token. Your client-side code (the app that performs the actual user sign-in), should make sure it sends the most current ID token to the Node.js server with each request. And make sure the Node.js server doesn't cache the ID tokens or otherwise keep them in-memory as part of application state.

Thanks,
Hiranya



--

Hiranya Jayathilaka | Software Engineer | h...@google.com | 650-203-0128

Adam Weisberg

unread,
Feb 27, 2020, 12:46:26 AM2/27/20
to fireba...@googlegroups.com
How is the user interacting with the Node backend? Is it though the same client app that they used to log in initially? If so, run the code in the CLIENT to refresh the token, or just generate a new token when the user needs to reach out to your Node backend, and send the new token.

Reply all
Reply to author
Forward
0 new messages