Wajahath
Wajahath

Reputation: 4068

How to share token between Firebase and server?

My Node.js app uses Firebase products as well as a server running in App Engine. So when a user is signed in, he should be able to authenticate on both platforms. I used custom tokens for this.

In server, I called admin.auth().createCustomToken(uid) and sent that token to client.
In client, I used firebase.auth().signInWithCustomToken(token) and signed in. All good.

I also read regarding the token exp field

The time, in seconds since the UNIX epoch, at which the token expires. ... But once you sign a user in using signInWithCustomToken(), they will remain signed in into the device until their session is invalidated or the user signs out.

So the Firebase handles the token refresh and all (please correct me if I'm wrong), which I don't have to worry about. Moreover, Firebase and my app uses the same keys (service account keys) to generate the token.

Custom tokens are signed JWTs where the private key used for signing belongs to a Google service account.

So a token generated is compatible between firebase and the server.

Now, where I'm stuck is, I need token to authenticate to App Engine server. How to get the latest (non-expired) token from firebase after doing a successful firebase.auth().signInWithCustomToken(token)?

I could have used the token in signInWithCustomToken(token). But this may me expired after an hour. So I thought I could depend on the firebase authentication.

Thanks.

Upvotes: 1

Views: 322

Answers (1)

Frank van Puffelen
Frank van Puffelen

Reputation: 600130

The short-lived token that Firebase SDKs auto-refresh is called an ID token, and you can get it by calling getIDToken(false) on the user object. This gives you the current ID token, so there's a chance it may expire relatively quickly - although usually not for at least 5 minutes, as the SDK requests a new ID token at that point.

You can also force the SDK to refresh the token by calling getIDToken(true), which means you get a token that's valid for about an hour.

Upvotes: 1

Related Questions