简体   繁体   中英

Firebase Authentication - Logged In User Is Null

I have managed to setup a custom login system using Firebase. The user enters email/password and is redirected to the main page(which is private). I am having issue with onAuthStateChanged after logging in. When I check the auth state after logging into the main page, i get invalid user (null). The firebase dashboard shows I have logged in successfully but onAuthStateChanged is the opposite.

I am trying to check if a user is logged in to my html pages, if not I want to redirect them to the login page. I like how the authentication works in firebase but I need to protect my html pages not my divs (which is what the vast majority of firebase auth tutorials show).

If anyone has an easier way to password protect a web directory that looks nicer than HTaccess, please advise (I am not crazy about using wordpress for password protection, but its an option). Otherwise, I guess I will have to do this in PHP. Thanks in advance!

(function () {
   firebase.auth().onAuthStateChanged(function(user) {
      if (user) {
        // User is signed in.
         console.log(user);
         console.log('A user is logged in.');
      } else {
        // No user is signed in.
        console.log('Invalid user. Redirecting to root.');
        window.location.replace('../index.html');
      }
   });
})();

If you navigate to a new page, Firebase will have to initialize again. As part of that it will try to restore the user's authentication state, but this requires a call to the server which takes time.

For that reason the onAuthStateChanged listener will initially fire with null as the current user (and auth.currentUser is set to null ). Then once the user is signed in, the listener fires again with the user object for that user.

If you want to detect this initial state, you can either store some token value in the browser's local storage that you can check for yourself on the new page, or you could set a time-out for when you expect the user to be re-signed in and only then navigate away to the index.html page.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM