Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to handle expired user ID token in firebase?

I am using Firebase authentication to authenticate users. Whenever, the user is logged in, I get the user's ID token with user.getIdToken(true) and set it on the local storage. With that token in the authorization header, I am requesting my back-end API.

On the back-end side, I am using Firebase admin SDK to authenticate the request and the user with the client-side ID token passed in the request authorization header.

This works for a while. But after some time I get error:

ExpiredIdTokenError: Token expired, 1620908095 < 1620915515

I saw that Firebase refreshes the ID token on its own. But I don't think that's the case. I have looked through the developer tools network tab, and there's also an observer method to check whenever the token has changed => onIdTokenChanged(), but the token is never refreshed.

I couldn't find any information on the Firebase docs either, and I was hoping if you could help me:

  • How can I generate a token without expiration limit to last until signed out or at least for some more time (1 week maybe)?
  • If I cannot the set the expiry limit of the token, what steps should I take so that I can send a valid unexpired token when I am request data from my back-end? Do I have to call user.getIdToken(true) every-time and get a fresh token before I request from my back-end API?
like image 281
Msw Tm Avatar asked Sep 07 '25 06:09

Msw Tm


1 Answers

The idTokenChanged() observer is a bit misleading. It will fire when the token is refreshed, but the token is only refreshed automatically when you also use other Firebase products (like its database or file storage). In other cases, as you said you should call user.getIdToken(), which will refresh an expired token for you if necessary, everytime you call your API. You don't need to pass true into this method unless you want to have a completely fresh token everytime (which you most likely don't need).

To my knowledge you cannot control the expiration of tokens generated with the client SDK, for that you would need to generate your own tokens on the server.

like image 158
puelo Avatar answered Sep 09 '25 20:09

puelo