Andro
Andro

Reputation: 421

Firebase auth idTokens

I have read so many articles about firebase auth on web but couldn't find any clear explanation of how idTokens are supposed to be used on the client side. Here is what I know so far

After the user has logged in, we can get the token using the following method and it will automatically refresh the token if it has expired

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

We can then send this token to our backend where we can use firebase admin SDK to verify the id token and get the user uid.

admin.auth().verifyIdToken(idToken).then(function(decodedToken) {
    var uid = decodedToken.uid;
    // ...
}).catch(function(error) {
    // Handle error
});

Here are the things which I don't understand.

  1. Do I need to call getIdToken() method before each API call to the server to get the idToken?
  2. Firebase documentation says that the token expires after 1 hour. So am I supposed to keep a track of that using localStorage and then reuse the token for 1 hour till it expires and then issue a new one using getIdToken()?
  3. Should I instead create a session on the backend with the uid which won't expire and then use that to verify if the user has logged in or not?

Upvotes: 1

Views: 567

Answers (1)

Matt
Matt

Reputation: 3180

  1. No; as you noted, the token is valid for an hour. You can reuse the same token during that period unless you have a reason to refresh it (for example, if you add custom claims)

  2. Ideally your server will return a 401 Unauthorized or something when the token is invalid. Most REST libraries provide the ability to add interceptors in the request chain, so you can check if you get back a 401 code and only refresh the token when necessary.

  3. There is no need for a backend session unless your business logic requires it. The Firebase library will handle persistence for you.

Upvotes: 1

Related Questions