如何在Firebase Auth中阻止未经登录权限的用户访问其他页面



我有一个网站,有多个页面,并使用Firebase作为后端。我已经实现了firebase认证的登录,我有使用onAuthChangeState的知识。问题是现在我试图找到一种方法来阻止用户访问其他页面没有登录页面。我想要一些类似"会话"或"标记"的东西;在PHP中,它充当用户访问页面的键。注意!我没有使用php,因为我也使用firebase作为托管我的站点的手段。顺便说一句,我看到的大多数资源只使用了一个页面,并且使用了很多样式。display = "none或block",我不想走这条路,因为我喜欢更有组织,并在代码隔离方面有适当的管理。这就是为什么我有很多页。Login.html Page2.html。

我知道如何使用javascript重定向
firebase.auth().onAuthStateChanged(firebaseUser => {
if(firebaseUser){
window.location.href = "page2.html";
}else{
window.location.href = "page1.html";
}
});

但是用户可能只输入https://mysite.firebaseapp.com/page2.html并访问它。这正是我想要阻止的。

如果我理解正确的话,您想要检查用户是否登录。如果用户已登录,则希望显示页面,如果用户未登录,则希望将其重定向到登录页面。如果我理解错了,请纠正我,但我将给出一个我上面描述的例子。

此代码必须放置在每个不允许用户在未登录的情况下访问的页面上。

firebase.auth().onAuthStateChanged(function(user) {
if(user) {
//Here you can place the code that you want to run if the user is logged in
} else {
window.location.href = "login.html";
}
});

解决方案是,我只需要创建一个脚本,具有

firebase.auth().onAuthStateChanged(function(user) {
if(user) {
//Here you can place the code that you want to run if the user is logged in
} else {
window.location.href = "login.html";
}
});

并按照Harith的建议把它包含在所有的页面上。

最新更新