【问题标题】:Firebase authentication does not authenticate when redirectedFirebase 身份验证在重定向时不进行身份验证
【发布时间】:2019-11-15 19:27:07
【问题描述】:

在我的网站中,默认页面是 index.html。如果用户未连接,则将他重定向到登录页面。当用户登录后,程序应该将他重定向回 index.html 并显示页面。但是,当我登录(并且凭据正确)时,它会再次将我重定向到登录页面。

这是索引页面的代码:

var user = firebase.auth().currentUser;

if (!user){
    window.location = 'https://anastasispap.me/auth/login.html';
}

登录页面代码:

const loginForm = document.querySelector('#login-form');

loginForm.addEventListener('submit', (e) => {
    e.preventDefault();

    const email = loginForm['login-email'].value;
    const password = loginForm['login-password'].value;
    console.log(email, password)

    auth.signInWithEmailAndPassword(email, password).then(cred => {
        console.log(cred)
        loginForm.reset()
        window.location.assign("https://anastasispap.me/index.html")

    })
})

感谢您的宝贵时间:)

【问题讨论】:

    标签: javascript html firebase firebase-authentication


    【解决方案1】:

    firebase.auth().currentUser 在页面加载时不会立即由当前用户填充。您应该附加一个AuthStateListener 来确定用户对象是否以及何时可用,如documentation 中所述。

    firebase.auth().onAuthStateChanged(function(user) {
      if (user) {
        // User is signed in.
      } else {
        // No user is signed in.
      }
    });
    

    【讨论】:

      猜你喜欢
      • 2021-11-27
      • 2020-04-01
      • 2022-12-10
      • 2017-03-11
      • 2015-09-23
      • 2019-08-09
      • 2019-03-23
      • 2011-04-30
      • 2016-07-09
      相关资源
      最近更新 更多