且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用 Nuxt 中间件进行用户重定向和身份验证

更新时间:2023-09-20 22:17:10

默认情况下,Firebase 会在身份验证成功后保持用户登录状态.此示例使用会话来存储用户 uid 和 cookie 以存储用户令牌,并在会话结束(例如浏览器关闭时)然后开始新会话但用户仍根据 Firebase 进行身份验证的情况下使用.在这种情况下,用户无需登录即可查看受保护的资源.

By default Firebase persists the users logged in status on successful authentication. This example uses the session, to store the user uid and cookies to store the users token and used in situations where the sessions has ended (example when browser is closed) and then a new session started but where the user is still authenticated according to Firebase. In cases like these the user will not need to sign in to view protected resources.

用于保护它的基本中间件应如下所示(如果您有一个名为 User 的 Store Module)

Your basic Middleware to protect it should look like this (if you have a Store Module called User)

export default function ({ store, redirect }) {
  if (!store.getters['modules/user/isAuthenticated']) {
    return redirect('/auth/signin')
  }
}

您的主要商店中使用ServerInit函数获取用户是否保存在Cookies中并将其加载到您的用户存储模块中,该模块将用于中间件中的验证.

In your main Store you use the ServerInit Function to get the User if there is one saved in the Cookies and load it into your User Store Module which will be used for verification in the Middleware.

您的用户存储模块应该看起来 像这样,并记住当您注销用户时删除 Cookie,以便他完全注销.

Your User Store Module should look like this, and keep in mind that you remove the Cookie when you Log the User out so that he is fully logged out.

我使用上面提到的东西作为我的身份验证的开始并对其进行了一些修改,您也可以这样做.大部分功劳归功于 davidroyer,他设置了这个不错的 Github 存储库 其中包含所有需要的文件,作为如何实现目标的一个很好的例子.

I used the things i mentioned above as the beginning of my Authentication and modified it a bit, which you can also do. Most of the credit goes to davidroyer who has set up this nice Github Repo which includes all needed files as a good example on how to accomplish your goal.