Search code examples
firebasefirebase-authenticationaccess-tokenfirebase-adminrefresh-token

How i get new access token when current access token has expired, google firebase auth?


I use firebase at client and use firebase-admin at server. At client i use signInWithPopUp to sign in to my web app with google account, then receive accessToken, expirationTime, refreshToken at client.

stsTokenManager:{
  accessToken: "eyJhbGciOiJzGcaUzI1JKKIsIzxcXzStpZC... ,
  expirationTime: 1648809531166 ,
  refreshToken: "AIwxAjDfh8_SkckvoSsASxXllMkIX8GBNx...

And i use verify function in firebase-admin lib for verify token was send by client, but until token has expired(1h), i can't use this token. How i get new accesstoken when current access token has expired?


Solution

  • You don't have to necessarily have to read user's idToken, store it anywhere or refresh it yourself. Instead you just need to use getIdToken() to get user's ID Token. If the token has expired, Firebase SDK will refresh and return a new token or return existing one. You can use getIdToken() before every request to your API.

    const userToken = await firebase.auth().currentUser.getIdToken();
    
    // pass userToken to in the API request
    // API request here