首页 > 解决方案 > 在 Firebase 中实施身份验证的正确方法是什么?

问题描述

好的,所以我在 Firebase 中构建了一些应用程序,并且真的很喜欢使用简单的 API,但总是与身份验证斗争。看到这个代码

我有一个简单的电子邮件和密码“表单”(不是表单元素,只有两个输入),然后是一个按钮(div)我点击下面调用这个函数

const logUserIn = () => {
    firebase
        .auth()
        .signInWithEmailAndPassword(email, password)
        .then((res) => {
            console.log('here') // this WORKS but the history redirect below does not work :/
            localStorage.setItem('authUser', JSON.stringify(res))
            history.push('/account')
        })
        .catch((error) => {
            console.log('ERROR:', error)
        })
}

但是当我把下面的行

    firebase.auth().onAuthStateChanged((user) => {
        if (user) {
            console.log('user logged in')
        } else {
            console.log('user not logged in')
        }
    })

它似乎正确地拿起它

但我的问题是,有什么意义signInWithEmailAndPassword?还有,我如何同时使用这两个功能?我需要调用我onAuthStateChanged.then部分signInWithEmailAndPassword功能吗?

如何拥有一致的状态真的很令人困惑。刷新页面后,我的应用程序似乎可以工作,但我希望它可以在不刷新的情况下工作(显然)

关于最佳方法的任何想法?

编辑

当我点击退出时

firebaseApp.auth().onAuthStateChanged((user) => {
    if (user) {
        history.push('/account')
    } else {
        console.log('NO USER')
    }
})

NO USER日志,但然后我单击经过身份验证的路线,它将带我到那里,直到我刷新

标签: javascriptfirebasefirebase-authentication

解决方案


重点signInWithEmailAndPassword是允许为没有 Google、Facebook、Twitter 等帐户的人实施经典的用户名/密码身份验证。如果您决定添加它,Google 将处理用户帐户和所有内容,但您必须构建登录表单,并填写我忘记密码注册为新用户链接。除此之外,它只是另一个提供商。

我的 Github repo 上有一个非常简单的小项目,它实现了用户/密码身份验证以及其他几个,我建议你研究一下。我把它作为工作面试的测试作业。是角。 https://github.com/tomcatmwi/morbidomega


推荐阅读