Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When to refresh expired Firebase3 (Web) Token for API request

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!

like image 779
Kenneth Truong Avatar asked Aug 16 '16 02:08

Kenneth Truong


People also ask

Which is the expired time of refresh token?

The refresh token is set with a very long expiration time of 200 days.

How do you refresh a Firebase token?

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.

How long does a Firebase token last?

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.


1 Answers

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.

like image 181
Kenneth Truong Avatar answered Sep 25 '22 23:09

Kenneth Truong