Search code examples
javascriptfirebasefirebase-authentication

How to detect idToken expiry?


I have a login page that authenticates users using signInWithEmailAndPassword() using Javascript client SDK.

If a login is successful, user is redirected (along with the idToken) to the member page.

On the server side (nodejs using firebase admin SDK), the member page checks the validity of idToken and if valid, it gets the user-specific data from Firebase and displays it on the webpage. On the member page, there is lots of data to see/edit/delete etc. So it's not inconceivable that a user might spend more than an hour in this page.

My problem is, I couldn't find a way to detect if the idToken has expired. Ideally I would like to refresh and get a new idToken. Is that possible? If that is not possible, I would like to redirect the user to login page when idToken expires.

But I am not able to figure out how to achieve either one. Looks like onAuthStateChanged and onIdTokenChanged are not triggered when idToken expires. And I am not able to do a forceRefresh of idToken like, firebase.auth().currentUser.getIdToken(true). Because on member page, firebase.auth().currentUser returns null.

Any suggestion on how to handle this scenario?

Thanks.


Solution

  • Using the Firebase Node.js Admin SDK, you can check for a revoked or expired ID token when calling verifyIdToken() by setting the checkRevoked parameter to true.

    verifyIdToken(idToken: string, checkRevoked?: boolean): Promise<DecodedIdToken>

    checkedRevoked: boolean
    Whether to check if the ID token was revoked. This requires an extra request to the Firebase Auth backend to check the tokensValidAfterTime time for the corresponding user. When not specified, this additional check is not applied.

    admin.auth().verifyIdToken(idToken, true)
      .then(function(decodedToken) {
        let uid = decodedToken.uid;
        // ...
      }).catch(function(error) {
        // Handle error for expired ID token
      });
    

    Alternatively, the ID token payload claims may be checked on the client. The documentation for how to Verify ID tokens using a third-party JWT library show the payload claims.

    exp expiration time: Must be in the future. The time is measured in seconds since the UNIX epoch.

    jwt.io references libraries that support client-side token verification.

    Also see: How to decode the JWT encoded token payload on client-side in angular 5?