question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

How can I refresh firebaseAccessToken from the browser?

See original GitHub issue

Hello, could someone point me how to refresh firebaseAccessToken from the browser?

I am using firebaseUI to auth in the browser, and send firebaseAccessToken to my hosted server via the cookie.

It is done by including the following script on pages where require authorization. Currently it redirects users to login page when the firebaseAccessToken is expired, and the token is refreshed on the login page within the firebaseUI’s sign-in box.

What I would like to achieve is to refresh the token within this script WITHOUT redirecting to the login page. I looked into the docs but could not find exact answer as I probably am not fully understand how the firebaseUI handles the token generation.

It would be awesome if someone could point me to any example or source code to refer to. Thanks a lot in advance!

<script>
  initApp = function() {
    firebase.auth().onAuthStateChanged(function(user) {
      if (user) {
        // User is signed in.
        user.getToken().then(function(accessToken) {
          document.cookie = "firebaseAccessToken=" + accessToken + '; path=/';
          if (document.getElementById("firebaseAccessToken")) {
            document.getElementById("firebaseAccessToken").value = accessToken;
          }
        });
      } else {
        // console.log('user signed-out');
        location.href = '/users/login?signInSuccessUrl=' + encodeURIComponent(window.location.pathname);
      }
    }, function(error) {
      console.log(error);
      // console.log(document.cookie);
    });
  };
   window.addEventListener('load', function() {
    initApp();
  });
</script>

Issue Analytics

  • State:closed
  • Created 6 years ago
  • Comments:9 (3 by maintainers)

github_iconTop GitHub Comments

4reactions
bojeil-googlecommented, May 22, 2017

Hey @goodpic you seem to be adding a firebase.auth().onAuthStateChanged (without unsubscribing it) on each poll which is not efficient. When a token change is detected, all previous listeners will trigger. How about this simpler logic which should work when the user is signed in or signed out.

onAuthStateChanged (add this observer to every page):
  clear any existing timer
  get saved ID token and expiration from cookie if available.
  if user
    getToken()
    if same saved token (should happen on page reload)
      set timer to same expiration time saved in cookie. this will run getToken(true) when triggered
    else
      Update cookie with new token and expiration (1 hour)
      set timer to next hour. this will run getToken(true)
    If this is an intermediate page (cookie was expired), redirect the user to the intended
    page that requires the user to be authenticated.
    This may happen if the user hasn't accessed your site in a while.
  else no user
    clear cookie if not already cleared.
    Redirect to login page unless already there. If already there, render Sign-in widget.
3reactions
goodpiccommented, May 13, 2017

This seems to be working fine.

<script>
initApp = function() {
  firebase.auth().onAuthStateChanged(function(user) {
    // Check user is signed in.
    if (user) {
      // Timer to force refresh firebaseAccessToken every 55 minutes.
      var refresh = false;
      var dt = new Date();
      var elapsed = 0;
      var cookie = "; " + document.cookie;
      var parts = cookie.split("; firebaseAccessTimer=");
      if (parts.length == 2) {
        elapsed = dt.getTime() - parts.pop().split(";").shift();
      }

      if (55*60*1000 < elapsed) {
        document.cookie = "firebaseAccessTimer=" + dt.getTime() + '; path=/';
        refresh = true;
      }
      user.getToken(refresh).then(function(accessToken) {
        document.cookie = "firebaseAccessToken=" + accessToken + '; path=/';
        if (document.getElementById("firebaseAccessToken")) {
          document.getElementById("firebaseAccessToken").value = accessToken;
        }
      });
    } else {
      // console.log('user signed-out');
      document.cookie = "firebaseAccessTimer=" + dt.getTime() + '; path=/';
       location.href = '/users/login?signInSuccessUrl=' + encodeURIComponent(window.location.pathname);
    }
  }, function(error) {
    document.cookie = "firebaseAccessTimer=" + dt.getTime() + '; path=/';
    console.log(error);
  });
};
window.addEventListener('load', function() {
  initApp();
});
</script>
Read more comments on GitHub >

github_iconTop Results From Across the Web

Manage User Sessions | Firebase Authentication - Google
Update user-specific metadata in Firebase Realtime Database. ... Save the refresh token revocation timestamp. This is needed to track ID token revocation via ......
Read more >
How to use the Firebase refreshToken to reauthenticate?
When you make call from a browser .getIdToken(true) will automatically refresh your token. Make call like this: firebase.auth().currentUser.
Read more >
Where Does Firebase Store its Authentication Tokens in Web ...
The stsTokenManager field in the value object has both the access and refresh tokens along with the expiration time of the access token....
Read more >
Using OAuth 2.0 to Access Google APIs | Authorization
The application should store the refresh token for future use and use the access token to access a Google API. Once the access...
Read more >
Demystifying Firebase Auth Tokens | by Jacob Wenger
Come learn about the Firebase client SDK authentication model. ... The refresh token is a standard OAuth 2.0 refresh token, which you can ......
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found