javascript - Firebase 身份验证在页面刷新时消失
问题描述
我有一个使用 firebase 身份验证的简单反应应用程序。成功登录后,firebase:authUser存储在 localStorage 中。但是在每次页面刷新时,localStorage 都会被清除并且会话丢失。浏览其他页面并不会清除 localStorage。
这是它在代码中的样子:
- 索引.js
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';
ReactDOM.render(
<React.StrictMode>
<App />
</React.StrictMode>,
document.getElementById('root')
);
reportWebVitals();
- 应用程序.js
import { BrowserRouter as Router, Route, Routes } from "react-router-dom";
import Login from './Login';
import Main from './Main';
import Info from './Info';
import './App.css';
function App() {
return (
<div className="App">
<Router>
<Routes>
<Route path="/login" element={<Login/>} />
<Route path="/" element={<Main/>} />
<Route path="/info" element={<Info/>} />
</Routes>
</Router>
</div>
);
}
export default App;
- Info.js → 无需身份验证即可查看的随机页面。在此页面 (http://localhost:3000/info) 上刷新也会清除 localStorage
import { useNavigate } from "react-router-dom";
function Info() {
const navigate = useNavigate();
return (
<div>
<div>
Info page
</div>
<button
onClick={() => {
navigate('/');
}
}>
Go to Main
</button>
</div>
);
}
export default Info;
这是我用来验证用户身份的 firebase.js
import { initializeApp } from 'firebase/app';
import { getAuth, createUserWithEmailAndPassword, signInWithEmailAndPassword, signOut, setPersistence, browserLocalPersistence } from 'firebase/auth';
const firebaseConfig = {
// Here is my config
};
initializeApp(firebaseConfig);
// Auth
const auth = getAuth();
var email;
var password;
// Auth - set persistance
setPersistence(auth, browserLocalPersistence);
// Auth - create
createUserWithEmailAndPassword(auth, email, password)
.then((userCredential) => {
// Signed in
const user = userCredential.user;
})
.catch((error) => {
const errorCode = error.code;
const errorMessage = error.message;
});
// Auth - Login
signInWithEmailAndPassword(auth, email, password)
.then((userCredential) => {
// Signed in
const user = userCredential.user;
})
.catch((error) => {
const errorCode = error.code;
const errorMessage = error.message;
});
// Auth - signOut
signOut(auth).then(() => {
// Sign-out successful.
}).catch((error) => {
// An error happened.
});
export {
auth,
db,
createUserWithEmailAndPassword,
signInWithEmailAndPassword,
signOut
};
解决方案
在大多数浏览器中,当您重新加载页面时,Firebase 已经默认从本地存储恢复用户身份验证状态。但是由于这需要它调用服务器,它可能需要一段时间才能初始化当前用户,您应该使用所谓的身份验证状态侦听器,如获取当前用户的文档中的第一个代码示例所示:
import { getAuth, onAuthStateChanged } from "firebase/auth";
const auth = getAuth();
onAuthStateChanged(auth, (user) => {
if (user) {
// User is signed in, see docs for a list of available properties
// https://firebase.google.com/docs/reference/js/firebase.User
const uid = user.uid;
// ...
} else {
// User is signed out
// ...
}
});
您的代码似乎只处理用户显式登录的情况,因此它永远不会选择恢复的用户。
如果上述方法有效,请检查您是否真的需要调用setPersistence(auth, browserLocalPersistence);
. 如前所述,在浏览器上,这应该已经是默认行为。
推荐阅读
- javascript - 如何在 nivo 图表设置中添加自定义颜色主题
- javascript - 如何使用 ssl 客户端身份验证 fetch()?
- java - 为什么我的 API 没有为我的 minecraft-Plugin 加载?
- cookiecutter-django - 只是为了确定:cookiecutter-django 没有注销端点,对吗?
- c - 指针存储哪些地址?
- python - 当所有元素都已经填满时打破游戏
- html - Pug 没有将查询中的 JSON 呈现到表中
- python - Raspberry 启动脚本未运行
- swift - 根据条件从 JSON 中获取值
- for-loop - 如何使用for在ansible中嵌套变量