How can I refresh firebaseAccessToken from the browser?
See original GitHub issueHello, 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:
- Created 6 years ago
- Comments:9 (3 by maintainers)
Top GitHub Comments
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.
This seems to be working fine.