[英]Passport JS authentication returning false when logging in from front-end side
[英]Firebase authentication returning false when reloading the page
我目前正在使用 Firebase 集成和反应的项目。 我可以注册和登录,但我确实想要一些 Guard,以便在我连接时访问“已连接”页面,或者如果我没有,则重定向到断开连接的 state 的默认页面。
我编写了以下代码以获得不同的路由并将其设置在 App.tsx 文件中:
const ConnectedRoute: React.FC<RouteProps> = ({ component, ...rest }) => {
var route = <Route />
var connected = isConnected()
console.log(connected)
if (connected){
route = <Route {...rest} component={component}/>
}
else{
route = <Route {...rest} render={() => <Redirect to ="/welcome" />} />
}
return route
}
const UnconnectedRoute: React.FC<RouteProps> = ({ component, ...rest }) => {
var route = <Route />
var connected = isConnected()
console.log(connected)
if (connected){
route = <Route {...rest} render={() => <Redirect to ="/home" />} />
}
else{
route = <Route {...rest} component={component}/>
}
return route
}
const App: React.FC = () => {
return (
<IonApp>
<IonReactRouter>
<IonRouterOutlet>
<Route exact path="/" render={() => <Redirect to="/welcome" />} />
<UnconnectedRoute path="/welcome" component={UnconnectedHome} exact />
<ConnectedRoute path="/home" component={ConnectedHome} exact />
<UnconnectedRoute path="/login" component={Login} exact />
<UnconnectedRoute path="/register" component={Register} exact />
<ConnectedRoute path="/events/create" component={CreateEvent} exact />
</IonRouterOutlet>
</IonReactRouter>
</IonApp>
)
};
对于 firebase 初始化,我执行了以下操作:
export async function initializeApp(){
console.log("Checking if app is initialized...")
if (firebase.apps.length == 0){
console.log("App initializing...")
firebase.initializeApp(firebaseConfig);
await firebase.auth().setPersistence(firebase.auth.Auth.Persistence.LOCAL)
}
}
function 知道用户是否已连接(作为 cookie)是这个:
export function isConnected(){
const res = firebase.auth().currentUser
console.log(res)
return res !== null
}
尽管如此,当我重新加载标签时,它总是返回我FALSE !
所以,我想知道如何在应用程序启动之前初始化 firebase 服务器? 这是当前的问题吗? 我目前对此一无所知,这让我非常沮丧......
如果你已经遇到过这样的问题,那真的对我有帮助!
谢谢 !
Firebase 身份验证将用户的身份验证 state 保存在本地存储中。 但是当您加载新页面(或重新加载现有页面)时,它必须与服务器检查身份验证 state 是否仍然有效。 并且此检查需要一些时间,在此期间还没有当前用户。
绕过这种竞争条件的典型方法是使用 auth state 侦听器来检测当前用户:
firebase.auth().onAuthStateChanged(function(user) {
if (user) {
// User is signed in, redirect to "connected" pages
} else {
// No user is signed in, probably require them to sign in
}
});
我试图用代码在评论中回答,它没有用。
我现在这样做了(它不是那么好,但至少它有效):
const connectedPaths =
[
"/home",
"/events/create"
]
const unconnectedPaths =
[
"/welcome",
"/login",
"register"
]
firebase.initializeApp(firebaseConfig);
firebase.auth().onAuthStateChanged(function(user) {
if (user) {
if (!connectedPaths.includes(window.location.pathname)) window.location.href = "/home"
}
else {
if (!unconnectedPaths.includes(window.location.pathname)) window.location.href = "/welcome"
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.