简体   繁体   中英

authData is null after redirecting to another page

I have two small web apps and I'm redirecting from the first one to the second one after a login with Firebase. My current problem is that the Authentication data is not saved and get's null after the new page is loaded.

var ref = new Firebase("https://xxx.firebaseio.com");
var credentials = {};
credentials.email = email;
credentials.password = password;

ref.authWithPassword(credentials, function(error, authData) {
  if (error) {
      console.log("Login Failed!", error);
      document.getElementById("login-status").innerHTML = error;
  } else {
    console.log("Authenticated successfully with payload:", authData);
    console.log("AuthData expires: " + authData.expires);
    window.location = "http://localhost:3000/";
  }
});

So, first I'll get logged in correctly and authData shows the login details, but on the new page http://localhost:3000/ authData is null.

Does anyone know how to keep the session? I played around with the remember object but it didn't solve my problem.

Firebase Authentication automatically persists the session in the browser's local storage. So when you get to the new page, the user is already authenticated.

But your code doesn't detect this, because you're only handling the case where you actively authenticate the user.

The solution is to also monitor the authentication state . From that documentation:

// Register the callback to be fired every time auth state changes
ref.onAuth(function(authData) {
  if (authData) {
    console.log("User " + authData.uid + " is logged in with " + authData.provider);
  } else {
    console.log("User is logged out");
  }
});

If you put this snippet in the new page, it will detect that the user is already signed in.

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