Home > OS >  How to generate new id tokens for custom backend with firebase auth?
How to generate new id tokens for custom backend with firebase auth?

Time:02-16

We have built a custom nodejs backend but the authentication is using firebase auth with idtoken, the idtokens expire after 1 hour and the user is automatically logged out. When using firestore this is handled automatically, we have seen solutions that suggest a service worker but that has not worked.

Can someone please suggest a stable solution for this may be a middleware on the backend API's that can regenerate the tokens?

Thanks

CodePudding user response:

The user is not logged out and that is why Firestore keeps working. You can use getIdToken() method again to get user's ID Token and then pass it in API request.

firebase.auth().currentUser.getIdToken(/* forceRefresh */ true).then(function(idToken) {
  // Send token to your backend via HTTPS
  // ...
}).catch(function(error) {
  // Handle error
});

CodePudding user response:

The normal approach (which the Firebase services themselves use too) is to always the current token with each request to the backend service, so that the service has at least 5m to complete the request (which is a lot more than most services need).

If you need a token that can be used for longer, you can consider forcing a refresh of the token before you call the service as Dharmaraj pointed out in their answer.

Alternative, you can switch to using session cookies for the user, which can have an expiration of up to two weeks.

  • Related