I'm currently using firebase.auth().createUserWithEmailAndPassword(email, password)
to authenticate users and using the JWT token from firebase.auth().currentUser.getToken(true)
for API requests. However, Firebase is invalidating the token after 1 hour. So I'm wondering how should I refresh the token. Do I have to use my own custom token generation to properly utilize token refreshing?
I'm currently using this though I only tested it once but it seems to work.
firebase.auth().onAuthStateChanged(function () { // Refresh token here })
I've been reading the docs over and over again and haven't seen any mentions of refreshing the tokens for the Web Apps. I've also looked at example repositories for firebase and have not seen anyone use onAuthStateChanged for something like this. So I'm wondering is this the right approach for client side token refresh? The reason why I feel this might not be the best approach is because this might have a race condition. For example if the token expires and I send an API request with the old token before I refresh the token then my API request will have an auth failure for token expiration.
This is very similar to the question in Firebase DB HTTP API Auth: When and how to refresh JWT token? but slightly different in the sense that the question is for using Python and no mentions of onAuthStateChanged
.
Thanks!
The refresh token is set with a very long expiration time of 200 days.
You can refresh a Firebase ID token by issuing an HTTP POST request to the securetoken.googleapis.com endpoint. The refresh token's grant type, always "refresh_token". A Firebase Auth refresh token. The number of seconds in which the ID token expires.
The Firebase Admin SDK has a built-in method for creating custom tokens. At a minimum, you need to provide a uid , which can be any string but should uniquely identify the user or device you are authenticating. These tokens expire after one hour.
For those who came into this post looking for an answer. You can grab the token right before all your API calls to get the token.
// Make sure you don't pass in true which will always refresh the token
firebase.auth().currentUser.getToken()
Firebase will internally determine if the token needs to be refreshed or grab from cache. If you notice Firebase will not send any network requests until the token is expired.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With