简体   繁体   English

如果未通过身份验证,则将用户重定向到页面加载时的登录屏幕(Nuxt-firebase)

[英]Redirect users to login screen on page load if not authenticated (Nuxt-firebase)

I'm trying to setup navigation guards in my Nuxt app to redirect users to the login screen if they are not authenticated via Firebase Authentication.我正在尝试在我的 Nuxt 应用程序中设置导航守卫,以便在用户未通过 Firebase 身份验证进行身份验证时将用户重定向到登录屏幕。 When the user attempts to navigate my router middleware is redirecting them successfully, but on page load they are not being redirected.当用户尝试导航时,我的路由器中间件成功重定向了他们,但在页面加载时他们没有被重定向。

I did realize that the middleware is not even being fired on page load.我确实意识到中间件甚至没有在页面加载时被触发。 I found a recommendation to try a plugin to handle the redirect on page load, but it is not working.我找到了尝试使用插件来处理页面加载重定向的建议,但它不起作用。 Calling router.push from within the plugin does not redirect the user.从插件中调用 router.push 不会重定向用户。

Here are a few notes on my setup.以下是关于我的设置的一些注意事项。 This is being deployed to firebase hosting directly as a SPA with no SSR.这将作为没有 SSR 的 SPA 直接部署到 firebase 托管。 It's using the Nuxt-Firebase module with Firebase Authentication service.它使用带有 Firebase 身份验证服务的 Nuxt-Firebase 模块。

// nuxt.config.js

  target: "server", // server here works when I deploy to firebase, but I also tried static
  ssr: false,
  middleware: ["auth"],
  plugins: [
    "~/plugins/auth.js",
  ],
  modules: [
    [
      "@nuxtjs/firebase",
      {
        services: {
          auth: {
            initialize: {
              onAuthStateChangedMutation:
                "authData/ON_AUTH_STATE_CHANGED_MUTATION",
              onAuthStateChangedAction: "authData/ON_AUTH_STATE_CHANGED_ACTION",
              subscribeManually: false,
            },
          },
        },
      },
    ],
  ],
};

Here's a sample plugin I thought might solve this, but calling handleLoggedOut appears to do nothing on page load.这是我认为可以解决此问题的示例插件,但调用 handleLoggedOut 似乎对页面加载没有任何作用。

// --- plugin to redirect user --- /plugins/auth.js   ---
export default function (context, inject) {
  const auth = {
    handleLoggedOut: () => {
      console.log("logout handled");
      context.redirect("/login");
    },
  };
  inject("auth", auth);
}

// --- store actions --- /store/authData.js  ---
  actions: {
    async ON_AUTH_STATE_CHANGED_ACTION(
      { commit, state, dispatch },
      { authUser, claims }
    ) {
      if (authUser) {
         // logged in
      }
      else {
         // attempting to redirect here does not work
         this.$auth.handleLoggedOut()
      }
   }

I'm new to Nuxt and I can't seem to find an example that solves my issue.我是 Nuxt 的新手,我似乎找不到解决我的问题的例子。

Any help would be greatly appreciated, thank you!任何帮助将不胜感激,谢谢!

Code seems fine, But you can just use the this.$fire.auth.signOut() and you can remove the auth plugin.代码看起来不错,但是您可以只使用this.$fire.auth.signOut()并且可以删除 auth 插件。

Example:例子:

// --- store actions --- /store/authData.js --- // --- 存储操作 --- /store/authData.js ---

actions: {
    async signOut({ commit }, payload) {
        try {
           await this.$fire.auth.signOut();
           // This is just a guard to avoid navigation guard error (NavigationDuplicated), 
           // you can remove the if block
           if (!payload) {
              this.$router.push('/login')
           }
           commit(ON_AUTH_STATE_CHANGED_MUTATION, { authUser: null})
        } catch(err) {
           console.log(err)
        }

    },
async ON_AUTH_STATE_CHANGED_ACTION(
      { commit, state, dispatch },
      { authUser, claims }
    ) {
      if (authUser) {
         // logged in
      }
      else {
         // attempting to redirect here does not work
         return dispatch('signOut')
      }
   }

} }

The solution for redirecting users to the login on page load was to put this in my auth middleware:将用户重定向到页面加载登录的解决方案是将其放在我的身份验证中间件中:

export default function ({ redirect, store, route }) {
  // https://nuxtjs.org/docs/internals-glossary/context#redirect
  if (!store || !store.getters || !store.getters["authData/isLoggedIn"]) {
    window.onNuxtReady(() => {
      window.$nuxt.$router.push("/login");
    });
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Nuxt + Firebase 登录后重定向到受限页面 - Nuxt + Firebase redirect to restricted page after login Web 仅适用于经过身份验证的用户 Firebase - Web only for authenticated users Firebase 将 Firebase 认证用户与 Flutter 中的“用户”集合链接 - Linking Firebase Authenticated user with 'users' collection in Flutter 为什么 Google Analytics 和 Firebase 认证用户之间的活跃用户存在差异? - Why is there a discrepancy of active users between Google Analytics and Firebase authenticated users? 我希望将经过身份验证的匿名用户重定向到另一个页面 - I want anonymous authenticated users to be redirected to another page 重定向页面登录谷歌 - Redirect Page Login google 在 Firebase 上反应的登录页面 - Login Page With React On Firebase 如何只允许经过身份验证的用户在 Firebase Firestore 中创建集合? - How to allow only authenticated users to create a collection in Firebase Firestore? 使用多租户时在 Firebase 模拟器中查看经过身份验证的用户 - View authenticated users in Firebase Emulator when using multi tenancy 在初始页面加载时获取用户 - Nuxt 中间件 - Get user on initial page load - Nuxt middleware
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM