【问题标题】:How to prevent a web page from being viewed after click log out button?单击注销按钮后如何防止网页被查看?
【发布时间】:2019-09-05 09:57:35
【问题描述】:

我正在尝试使用 firebase 实时数据库制作一个简单的网站。我没有使用 PHP 来包含会话,因为我不知道如何将 PHP 与 firebase 一起使用。我确实阅读了文档,但我无法实现它。如何创建会话以防止用户在注销后单击返回按钮时能够查看上一页。

下面的代码可以运行,但是用户可以在点击返回按钮时查看上一页。

firebase.auth().onAuthStateChanged(function(user) {
        if (user) {
            // User is signed in.
            console.log('User is signed in.');
        } else {
            // No user is signed in.
            console.log('No user is signed in.');
            window.location ='login.html'; 
        }
    });

【问题讨论】:

  • 您可以使用JSONWEBTOKEN 创建一个令牌并将令牌存储在您的本地存储中,或者您可以使用js-cookie 将令牌存储到您的cookie 中,您可以将中间件传递给您的页面进行检查如果经过身份验证
  • if (user) {user.getIdToken().then(function(idToken) {});如果我使用此代码获得令牌,我接下来应该做什么?

标签: javascript html firebase firebase-realtime-database


【解决方案1】:

您需要具备 3 个功能:

第一

如果浏览器仍有该 cookie,您需要使用下面的 initAuth() 函数检查页面的初始加载。

第二次

您需要创建登录/注册方法以使您的用户拥有他们的令牌。

第三

你需要让用户退出。

它应该看起来像这样:

authenticateUser(content, authData) {
  let authUrl =
    "https://www.googleapis.com/identitytoolkit/v3/relyingparty/verifyPassword?key=" +
    process.env.fbAPIKey;
  if (!authData.isLogin) {
    authUrl =
      "https://www.googleapis.com/identitytoolkit/v3/relyingparty/signupNewUser?key=" +
      process.env.fbAPIKey;
  }
  return this.$axios
    .$post(authUrl, {
      email: authData.email,
      password: authData.password,
      returnSecureToken: true
    })
    .then(result => {
      content.commit("setToken", result.idToken);
      localStorage.setItem("token", result.idToken);
      localStorage.setItem(
        "tokenExpiration",
        new Date().getTime() + Number.parseInt(result.expiresIn) * 1000
      );
      Cookie.set("jwt", result.idToken);
      Cookie.set(
        "expirationDate",
        new Date().getTime() + Number.parseInt(result.expiresIn) * 1000
      );
      return this.$axios.$post('http://localhost:3000/api/track-data', {data: 'Authenticated!'})
    })
    .catch(e => console.log(e));
}

initAuth(content, req) {
  let token;
  let expirationDate;
  if (req) {
    if (!req.headers.cookie) {
      return;
    }
    const jwtCookie = req.headers.cookie
      .split(";")
      .find(c => c.trim().startsWith("jwt="));
    if (!jwtCookie) {
      return;
    }
    token = jwtCookie.split("=")[1];
    expirationDate = req.headers.cookie
      .split(";")
      .find(c => c.trim().startsWith("expirationDate="))
      .split("=")[1];
  } else if (process.client) {
    token = localStorage.getItem("token");
    expirationDate = localStorage.getItem("tokenExpiration");
  }
  if (new Date().getTime() > +expirationDate || !token) {
    console.log("No token or invalid token");
    content.dispatch("logout");
    return;
  }
  content.commit("setToken", token);
}

logout(content) {
  content.commit("clearToken");
  Cookie.remove("jwt");
  Cookie.remove("expirationDate");
  if (process.client) {
    localStorage.removeItem("token");
    localStorage.removeItem("tokenExpiration");
  }
}

中间件

然后你可以像这样调用你的中间件:

先检查Token:

context.store.dispatch("initAuth", context.req);

if (!context.store.getters.isAuthenticated) {
    context.redirect("/admin/login");
  }

这只是我的观点和我的示例代码。

【讨论】:

    【解决方案2】:

    这取决于您要保护的前一页上的哪些内容。如果它来自 Firebase 实时数据库,您通常可以使用 security rules 保护它。如果内容来自 Firebase 托管上的 HTML/JavaScript,则无法将其保护为 all content on Firebase Hosting is public

    【讨论】:

    • "rules": { "users": {"$uid": {".write": "$uid === auth.uid"} 。是这样的吗?
    • 这确实是一套安全规则。您需要的确切规则取决于您的具体情况,因此我们不可能只用笼统的术语回答这个问题。
    【解决方案3】:

    您包含的代码在用户登录/注销时进行处理。如果您不希望将页面提供给用户,除非他们已登录,否则您需要在页面上设置某种保护措施。适合您的解决方案取决于您如何实现路由。

    假设您没有中间件并且一切都在 firebase/您的应用程序中运行,您只需要确保当应用程序路由到新页面(应受登录保护)时,您的代码会拦截并检查用户是否已登录。您的 firebase.auth().onAuthStateChanged() 处理程序只是将用户重定向到登录屏幕,这就是它的全部用途。您将需要自己实现某种路由保护,就像拥有用于检索数据的保护一样。

    【讨论】:

    • 现在我可以直接访问新页面,但它会提示没有用户登录。如何保护这个新页面?
    • 这取决于您用于前端的框架。您需要在您的应用中找到向客户端提供页面的位置,并插入某种中间件来测试是否应允许用户执行该操作。
    猜你喜欢
    • 2023-02-21
    • 2020-10-19
    • 1970-01-01
    • 2012-05-17
    • 1970-01-01
    • 2017-02-01
    • 1970-01-01
    • 2012-05-14
    • 1970-01-01
    相关资源
    最近更新 更多