简体   繁体   English

Firebase 身份验证 - 登录用户是 Null

[英]Firebase Authentication - Logged In User Is Null

I have managed to setup a custom login system using Firebase.我已经设法使用 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).登录后我遇到 onAuthStateChanged 问题。当我登录主页后检查身份验证 state 时,我得到无效用户(null)。 The firebase dashboard shows I have logged in successfully but onAuthStateChanged is the opposite. firebase 仪表板显示我已成功登录,但 onAuthStateChanged 却相反。

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.我正在尝试检查用户是否登录到我的 html 页面,如果没有,我想将它们重定向到登录页面。 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).我喜欢 firebase 中身份验证的工作方式,但我需要保护我的 html 页面而不是我的 div(这是绝大多数 firebase auth 教程所展示的)

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).如果有人有更简单的方法来密码保护看起来比 HTaccess 更好的 web 目录,请告知(我不喜欢使用 wordpress 进行密码保护,但它是一个选项)。 Otherwise, I guess I will have to do this in PHP.否则,我想我将不得不在 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.如果导航到新页面,Firebase 将不得不再次初始化。 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.作为其中的一部分,它将尝试恢复用户的身份验证 state,但这需要调用服务器,这需要时间。

For that reason the onAuthStateChanged listener will initially fire with null as the current user (and auth.currentUser is set to null ).出于这个原因, onAuthStateChanged侦听器最初将使用null作为当前用户触发(并且auth.currentUser设置为null )。 Then once the user is signed in, the listener fires again with the user object for that user.然后,一旦用户登录,侦听器将再次触发该用户的user object。

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.如果您想检测这个初始 state,您可以在浏览器的本地存储中存储一些令牌值,您可以在新页面上自行检查,或者您可以设置一个超时时间,以便您希望用户重新访问登录,然后导航到index.html页面。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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